blob: 3044024a049e7341c8861691be8e66c4053b172c [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"
Denys Vlasenkocbe0b7f2009-10-09 22:00:58 +020089#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko20b3d142009-10-09 20:59:39 +020090# include "random.h"
Denys Vlasenko76ace252009-10-12 15:25:01 +020091#else
92# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko20b3d142009-10-09 20:59:39 +020093#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000094#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020095# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000096#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000097
Denis Vlasenko1943aec2009-04-09 14:15:57 +000098
Denys Vlasenko8d7be232009-05-25 16:38:32 +020099/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000100#define LEAK_HUNTING 0
101#define BUILD_AS_NOMMU 0
102/* Enable/disable sanity checks. Ok to enable in production,
103 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
104 * Keeping 1 for now even in released versions.
105 */
106#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200107/* Slightly bigger (+200 bytes), but faster hush.
108 * So far it only enables a trick with counting SIGCHLDs and forks,
109 * which allows us to do fewer waitpid's.
110 * (we can detect a case where neither forks were done nor SIGCHLDs happened
111 * and therefore waitpid will return the same result as last time)
112 */
113#define ENABLE_HUSH_FAST 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000114
115
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000116#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000117# undef BB_MMU
118# undef USE_FOR_NOMMU
119# undef USE_FOR_MMU
120# define BB_MMU 0
121# define USE_FOR_NOMMU(...) __VA_ARGS__
122# define USE_FOR_MMU(...)
123#endif
124
Denis Vlasenko61befda2008-11-25 01:36:03 +0000125#if defined SINGLE_APPLET_MAIN
126/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000127# undef CONFIG_FEATURE_SH_STANDALONE
128# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000129# undef IF_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000130# define IF_FEATURE_SH_STANDALONE(...)
131# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denys Vlasenko673e9452009-05-27 14:39:35 +0200132# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko61befda2008-11-25 01:36:03 +0000133#endif
134
Denis Vlasenko05743d72008-02-10 12:10:08 +0000135#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000136# undef ENABLE_FEATURE_EDITING
137# define ENABLE_FEATURE_EDITING 0
138# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
139# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000140#endif
141
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000142/* Do we support ANY keywords? */
143#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000144# define HAS_KEYWORDS 1
145# define IF_HAS_KEYWORDS(...) __VA_ARGS__
146# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000147#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000148# define HAS_KEYWORDS 0
149# define IF_HAS_KEYWORDS(...)
150# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000151#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000152
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000153/* If you comment out one of these below, it will be #defined later
154 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000155#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000156/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000157#define debug_printf_parse(...) do {} while (0)
158#define debug_print_tree(a, b) do {} while (0)
159#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000160#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000161#define debug_printf_jobs(...) do {} while (0)
162#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000163#define debug_printf_glob(...) do {} while (0)
164#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000165#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000166#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000167
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000168#define ERR_PTR ((void*)(long)1)
169
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000170#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000171
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000172#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000173
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200174struct variable;
175
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000176static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
177
178/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000179 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000180 */
181#if !BB_MMU
182typedef struct nommu_save_t {
183 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200184 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000185 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000186 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000187} nommu_save_t;
188#endif
189
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000190typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000191 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000192#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000193 RES_IF ,
194 RES_THEN ,
195 RES_ELIF ,
196 RES_ELSE ,
197 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000198#endif
199#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000200 RES_FOR ,
201 RES_WHILE ,
202 RES_UNTIL ,
203 RES_DO ,
204 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000205#endif
206#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000207 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000208#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000209#if ENABLE_HUSH_CASE
210 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200211 /* three pseudo-keywords support contrived "case" syntax: */
212 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
213 RES_MATCH , /* "word)" */
214 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000215 RES_ESAC ,
216#endif
217 RES_XXXX ,
218 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000219} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000220
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000221typedef struct o_string {
222 char *data;
223 int length; /* position where data is appended */
224 int maxlen;
225 /* Protect newly added chars against globbing
226 * (by prepending \ to *, ?, [, \) */
227 smallint o_escape;
228 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000229 /* At least some part of the string was inside '' or "",
230 * possibly empty one: word"", wo''rd etc. */
231 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000232 smallint has_empty_slot;
233 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
234} o_string;
235enum {
236 MAYBE_ASSIGNMENT = 0,
237 DEFINITELY_ASSIGNMENT = 1,
238 NOT_ASSIGNMENT = 2,
239 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
240};
241/* Used for initialization: o_string foo = NULL_O_STRING; */
242#define NULL_O_STRING { NULL }
243
244/* I can almost use ordinary FILE*. Is open_memstream() universally
245 * available? Where is it documented? */
246typedef struct in_str {
247 const char *p;
248 /* eof_flag=1: last char in ->p is really an EOF */
249 char eof_flag; /* meaningless if ->p == NULL */
250 char peek_buf[2];
251#if ENABLE_HUSH_INTERACTIVE
252 smallint promptme;
253 smallint promptmode; /* 0: PS1, 1: PS2 */
254#endif
255 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200256 int (*get) (struct in_str *) FAST_FUNC;
257 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000258} in_str;
259#define i_getch(input) ((input)->get(input))
260#define i_peek(input) ((input)->peek(input))
261
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200262/* The descrip member of this structure is only used to make
263 * debugging output pretty */
264static const struct {
265 int mode;
266 signed char default_fd;
267 char descrip[3];
268} redir_table[] = {
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_CREAT|O_RDWR, 1, "<>" },
273 { O_RDONLY, 0, "<<" },
274/* Should not be needed. Bogus default_fd helps in debugging */
275/* { O_RDONLY, 77, "<<" }, */
276};
277
Eric Andersen25f27032001-04-26 23:22:31 +0000278struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000279 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000280 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000281 int rd_fd; /* fd to redirect */
282 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
283 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000284 smallint rd_type; /* (enum redir_type) */
285 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000286 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200287 * bit 0: do we need to trim leading tabs?
288 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000289 */
Eric Andersen25f27032001-04-26 23:22:31 +0000290};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000291typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200292 REDIRECT_INPUT = 0,
293 REDIRECT_OVERWRITE = 1,
294 REDIRECT_APPEND = 2,
295 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000296 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200297 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000298
299 REDIRFD_CLOSE = -3,
300 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000301 REDIRFD_TO_FILE = -1,
302 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000303
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000304 HEREDOC_SKIPTABS = 1,
305 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000306} redir_type;
307
Eric Andersen25f27032001-04-26 23:22:31 +0000308
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000309struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000310 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000311 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000312 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200313 smallint cmd_type; /* CMD_xxx */
314#define CMD_NORMAL 0
315#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200316
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200317/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200318#if ENABLE_HUSH_BASH_COMPAT
319# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000320#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200321
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200322/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200323//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200324// It is hard to implement correctly, it adds significant amounts of tricky code,
325// and all this is only useful for really obscure export statements
326// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
327// guards the code which implements it, but I have doubts it works
328// in all cases (especially with mixed globbed/non-globbed arguments)
329
330#if ENABLE_HUSH_FUNCTIONS
331# define CMD_FUNCDEF 3
332#endif
333
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200334 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
335 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000336#if !BB_MMU
337 char *group_as_string;
338#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000339#if ENABLE_HUSH_FUNCTIONS
340 struct function *child_func;
341/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200342 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000343 * When we execute "f1() {a;}" cmd, we create new function and clear
344 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200345 * When we execute "f1() {b;}", we notice that f1 exists,
346 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000347 * we put those fields back into cmd->xxx
348 * (struct function has ->parent_cmd ptr to facilitate that).
349 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
350 * Without this trick, loop would execute a;b;b;b;...
351 * instead of correct sequence a;b;a;b;...
352 * When command is freed, it severs the link
353 * (sets ->child_func->parent_cmd to NULL).
354 */
355#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000356 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000357/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
358 * and on execution these are substituted with their values.
359 * Substitution can make _several_ words out of one argv[n]!
360 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000361 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000362 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000363 struct redir_struct *redirects; /* I/O redirections */
364};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000365/* Is there anything in this command at all? */
366#define IS_NULL_CMD(cmd) \
367 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
368
Eric Andersen25f27032001-04-26 23:22:31 +0000369
370struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000371 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000372 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000373 int alive_cmds; /* number of commands running (not exited) */
374 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000375#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000376 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000377 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000378 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000379#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000380 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000381 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000382 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
383 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000384};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000385typedef enum pipe_style {
386 PIPE_SEQ = 1,
387 PIPE_AND = 2,
388 PIPE_OR = 3,
389 PIPE_BG = 4,
390} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000391/* Is there anything in this pipe at all? */
392#define IS_NULL_PIPE(pi) \
393 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000394
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000395/* This holds pointers to the various results of parsing */
396struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000397 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000398 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000399 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000400 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000401 /* last command in pipe (being constructed right now) */
402 struct command *command;
403 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000404 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000405#if !BB_MMU
406 o_string as_string;
407#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000408#if HAS_KEYWORDS
409 smallint ctx_res_w;
410 smallint ctx_inverted; /* "! cmd | cmd" */
411#if ENABLE_HUSH_CASE
412 smallint ctx_dsemicolon; /* ";;" seen */
413#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000414 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
415 int old_flag;
416 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000417 * example: "if pipe1; pipe2; then pipe3; fi"
418 * when we see "if" or "then", we malloc and copy current context,
419 * and make ->stack point to it. then we parse pipeN.
420 * when closing "then" / fi" / whatever is found,
421 * we move list_head into ->stack->command->group,
422 * copy ->stack into current context, and delete ->stack.
423 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000424 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000425 struct parse_context *stack;
426#endif
427};
428
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000429/* On program start, environ points to initial environment.
430 * putenv adds new pointers into it, unsetenv removes them.
431 * Neither of these (de)allocates the strings.
432 * setenv allocates new strings in malloc space and does putenv,
433 * and thus setenv is unusable (leaky) for shell's purposes */
434#define setenv(...) setenv_is_leaky_dont_use()
435struct variable {
436 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000437 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200438#if ENABLE_HUSH_LOCAL
439 unsigned func_nest_level;
440#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000441 int max_len; /* if > 0, name is part of initial env; else name is malloced */
442 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000443 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000444};
445
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000446enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000447 BC_BREAK = 1,
448 BC_CONTINUE = 2,
449};
450
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000451#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000452struct function {
453 struct function *next;
454 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000455 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000456 struct pipe *body;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200457# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000458 char *body_as_string;
Denys Vlasenkoc1947f12009-10-23 01:30:26 +0200459# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000460};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000461#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000462
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000463
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000464/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000465/* Sorted roughly by size (smaller offsets == smaller code) */
466struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000467 /* interactive_fd != 0 means we are an interactive shell.
468 * If we are, then saved_tty_pgrp can also be != 0, meaning
469 * that controlling tty is available. With saved_tty_pgrp == 0,
470 * job control still works, but terminal signals
471 * (^C, ^Z, ^Y, ^\) won't work at all, and background
472 * process groups can only be created with "cmd &".
473 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
474 * to give tty to the foreground process group,
475 * and will take it back when the group is stopped (^Z)
476 * or killed (^C).
477 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000478#if ENABLE_HUSH_INTERACTIVE
479 /* 'interactive_fd' is a fd# open to ctty, if we have one
480 * _AND_ if we decided to act interactively */
481 int interactive_fd;
482 const char *PS1;
483 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000484# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000485#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000486# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000487#endif
488#if ENABLE_FEATURE_EDITING
489 line_input_t *line_input_state;
490#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000491 pid_t root_pid;
Denys Vlasenkodea47882009-10-09 15:40:49 +0200492 pid_t root_ppid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000493 pid_t last_bg_pid;
Denys Vlasenko20b3d142009-10-09 20:59:39 +0200494#if ENABLE_HUSH_RANDOM_SUPPORT
495 random_t random_gen;
496#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000497#if ENABLE_HUSH_JOB
498 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000499 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000500 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000501 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400502# define G_saved_tty_pgrp (G.saved_tty_pgrp)
503#else
504# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000505#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000506 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000507#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000508 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000509#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000510#if ENABLE_HUSH_FUNCTIONS
511 /* 0: outside of a function (or sourced file)
512 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000513 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000514 */
515 smallint flag_return_in_progress;
516#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000517 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000518 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000519 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000520 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000521 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000522 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000523 /* how many non-NULL argv's we have. NB: $# + 1 */
524 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000525 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000526#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000527 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000528#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000529#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000530 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000531 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000532#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000533 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000534 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000535 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000536 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000537#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000538 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200539# if ENABLE_HUSH_LOCAL
540 struct variable **shadowed_vars_pp;
541 unsigned func_nest_level;
542# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000543#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000544 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200545#if ENABLE_HUSH_FAST
546 unsigned count_SIGCHLD;
547 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200548 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200549#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000550 /* which signals have non-DFL handler (even with no traps set)? */
551 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000552 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000553 sigset_t blocked_set;
554 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000555#if HUSH_DEBUG
556 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000557 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000558#endif
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +0200559 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000560};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000561#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000562/* Not #defining name to G.name - this quickly gets unwieldy
563 * (too many defines). Also, I actually prefer to see when a variable
564 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000565#define INIT_G() do { \
566 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
567} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000568
569
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000570/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200571static int builtin_cd(char **argv) FAST_FUNC;
572static int builtin_echo(char **argv) FAST_FUNC;
573static int builtin_eval(char **argv) FAST_FUNC;
574static int builtin_exec(char **argv) FAST_FUNC;
575static int builtin_exit(char **argv) FAST_FUNC;
576static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000577#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200578static int builtin_fg_bg(char **argv) FAST_FUNC;
579static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000580#endif
581#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200582static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000583#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200584#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200585static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200586#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000587#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200588static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000589#endif
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400590#if ENABLE_PRINTF
591static int builtin_printf(char **argv) FAST_FUNC;
592#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200593static int builtin_pwd(char **argv) FAST_FUNC;
594static int builtin_read(char **argv) FAST_FUNC;
595static int builtin_set(char **argv) FAST_FUNC;
596static int builtin_shift(char **argv) FAST_FUNC;
597static int builtin_source(char **argv) FAST_FUNC;
598static int builtin_test(char **argv) FAST_FUNC;
599static int builtin_trap(char **argv) FAST_FUNC;
600static int builtin_type(char **argv) FAST_FUNC;
601static int builtin_true(char **argv) FAST_FUNC;
602static int builtin_umask(char **argv) FAST_FUNC;
603static int builtin_unset(char **argv) FAST_FUNC;
604static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000605#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200606static int builtin_break(char **argv) FAST_FUNC;
607static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000608#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000609#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200610static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000611#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000612
613/* Table of built-in functions. They can be forked or not, depending on
614 * context: within pipes, they fork. As simple commands, they do not.
615 * When used in non-forking context, they can change global variables
616 * in the parent shell process. If forked, of course they cannot.
617 * For example, 'unset foo | whatever' will parse and run, but foo will
618 * still be set at the end. */
619struct built_in_command {
620 const char *cmd;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200621 int (*function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000622#if ENABLE_HUSH_HELP
623 const char *descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200624# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000625#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200626# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000627#endif
628};
629
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200630static const struct built_in_command bltins1[] = {
631 BLTIN("." , builtin_source , "Run commands in a file"),
632 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000633#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200634 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000635#endif
636#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200637 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000638#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200639 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000640#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200641 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000642#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200643 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
644 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
645 BLTIN("exit" , builtin_exit , "Exit"),
646 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000647#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200648 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000649#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000650#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200651 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000652#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000653#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200654 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000655#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200656#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200657 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200658#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000659#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200660 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000661#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200662 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000663#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200664 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000665#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200666 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
667 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
668 BLTIN("trap" , builtin_trap , "Trap signals"),
669 BLTIN("type" , builtin_type , "Write a description of command type"),
670// BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
671 BLTIN("umask" , builtin_umask , "Set file creation mask"),
672 BLTIN("unset" , builtin_unset , "Unset variables"),
673 BLTIN("wait" , builtin_wait , "Wait for process"),
674};
675/* For now, echo and test are unconditionally enabled.
676 * Maybe make it configurable? */
677static const struct built_in_command bltins2[] = {
678 BLTIN("[" , builtin_test , NULL),
679 BLTIN("echo" , builtin_echo , NULL),
Mike Frysinger4ebc76c2009-10-15 03:32:39 -0400680#if ENABLE_PRINTF
681 BLTIN("printf" , builtin_printf , NULL),
682#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200683 BLTIN("pwd" , builtin_pwd , NULL),
684 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000685};
686
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000687
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000688/* Debug printouts.
689 */
690#if HUSH_DEBUG
691/* prevent disasters with G.debug_indent < 0 */
692# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
693# define debug_enter() (G.debug_indent++)
694# define debug_leave() (G.debug_indent--)
695#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200696# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000697# define debug_enter() ((void)0)
698# define debug_leave() ((void)0)
699#endif
700
701#ifndef debug_printf
702# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
703#endif
704
705#ifndef debug_printf_parse
706# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
707#endif
708
709#ifndef debug_printf_exec
710#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
711#endif
712
713#ifndef debug_printf_env
714# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
715#endif
716
717#ifndef debug_printf_jobs
718# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
719# define DEBUG_JOBS 1
720#else
721# define DEBUG_JOBS 0
722#endif
723
724#ifndef debug_printf_expand
725# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
726# define DEBUG_EXPAND 1
727#else
728# define DEBUG_EXPAND 0
729#endif
730
731#ifndef debug_printf_glob
732# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
733# define DEBUG_GLOB 1
734#else
735# define DEBUG_GLOB 0
736#endif
737
738#ifndef debug_printf_list
739# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
740#endif
741
742#ifndef debug_printf_subst
743# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
744#endif
745
746#ifndef debug_printf_clean
747# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
748# define DEBUG_CLEAN 1
749#else
750# define DEBUG_CLEAN 0
751#endif
752
753#if DEBUG_EXPAND
754static void debug_print_strings(const char *prefix, char **vv)
755{
756 indent();
757 fprintf(stderr, "%s:\n", prefix);
758 while (*vv)
759 fprintf(stderr, " '%s'\n", *vv++);
760}
761#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200762# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000763#endif
764
765
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000766/* Leak hunting. Use hush_leaktool.sh for post-processing.
767 */
768#if LEAK_HUNTING
769static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000770{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000771 void *ptr = xmalloc((size + 0xff) & ~0xff);
772 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
773 return ptr;
774}
775static void *xxrealloc(int lineno, void *ptr, size_t size)
776{
777 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
778 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
779 return ptr;
780}
781static char *xxstrdup(int lineno, const char *str)
782{
783 char *ptr = xstrdup(str);
784 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
785 return ptr;
786}
787static void xxfree(void *ptr)
788{
789 fdprintf(2, "free %p\n", ptr);
790 free(ptr);
791}
792#define xmalloc(s) xxmalloc(__LINE__, s)
793#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
794#define xstrdup(s) xxstrdup(__LINE__, s)
795#define free(p) xxfree(p)
796#endif
797
798
799/* Syntax and runtime errors. They always abort scripts.
800 * In interactive use they usually discard unparsed and/or unexecuted commands
801 * and return to the prompt.
802 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
803 */
804#if HUSH_DEBUG < 2
Denys Vlasenko606291b2009-09-23 23:15:43 +0200805# define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000806# define syntax_error(lineno, msg) syntax_error(msg)
807# define syntax_error_at(lineno, msg) syntax_error_at(msg)
808# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
809# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
810# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000811#endif
812
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000813static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000814{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000815 va_list p;
816
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000817#if HUSH_DEBUG >= 2
818 bb_error_msg("hush.c:%u", lineno);
819#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000820 va_start(p, fmt);
821 bb_verror_msg(fmt, p, NULL);
822 va_end(p);
823 if (!G_interactive_fd)
824 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000825}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000826
827static void syntax_error(unsigned lineno, const char *msg)
828{
829 if (msg)
830 die_if_script(lineno, "syntax error: %s", msg);
831 else
832 die_if_script(lineno, "syntax error", NULL);
833}
834
835static void syntax_error_at(unsigned lineno, const char *msg)
836{
837 die_if_script(lineno, "syntax error at '%s'", msg);
838}
839
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400840static void syntax_error_unterm_str(unsigned lineno, const char *s)
841{
842 die_if_script(lineno, "syntax error: unterminated %s", s);
843}
844
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000845/* It so happens that all such cases are totally fatal
846 * even if shell is interactive: EOF while looking for closing
847 * delimiter. There is nowhere to read stuff from after that,
848 * it's EOF! The only choice is to terminate.
849 */
850static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000851static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000852{
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400853 char msg[2] = { ch, '\0' };
854 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000855 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000856}
857
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200858static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000859{
860 char msg[2];
861 msg[0] = ch;
862 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200863 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000864}
865
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000866#if HUSH_DEBUG < 2
867# undef die_if_script
868# undef syntax_error
869# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000870# undef syntax_error_unterm_ch
871# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000872# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000873#else
Denys Vlasenko606291b2009-09-23 23:15:43 +0200874# define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000875# define syntax_error(msg) syntax_error(__LINE__, msg)
876# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
877# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
878# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
879# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000880#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000881
Denis Vlasenko552433b2009-04-04 19:29:21 +0000882
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000883#if ENABLE_HUSH_INTERACTIVE
884static void cmdedit_update_prompt(void);
885#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200886# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000887#endif
888
889
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000890/* Utility functions
891 */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000892static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000893{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000894 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000895 return 0;
896 s++;
897 while (isalnum(*s) || *s == '_')
898 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000899 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000900}
901
Denis Vlasenko55789c62008-06-18 16:30:42 +0000902/* Replace each \x with x in place, return ptr past NUL. */
903static char *unbackslash(char *src)
904{
Denys Vlasenko71885402009-09-24 01:44:13 +0200905 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +0000906 while (1) {
907 if (*src == '\\')
908 src++;
909 if ((*dst++ = *src++) == '\0')
910 break;
911 }
912 return dst;
913}
914
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000915static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000916{
917 int i;
918 unsigned count1;
919 unsigned count2;
920 char **v;
921
922 v = strings;
923 count1 = 0;
924 if (v) {
925 while (*v) {
926 count1++;
927 v++;
928 }
929 }
930 count2 = 0;
931 v = add;
932 while (*v) {
933 count2++;
934 v++;
935 }
936 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
937 v[count1 + count2] = NULL;
938 i = count2;
939 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000940 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000941 return v;
942}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000943#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000944static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
945{
946 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
947 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
948 return ptr;
949}
950#define add_strings_to_strings(strings, add, need_to_dup) \
951 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
952#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000953
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200954/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000955static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000956{
957 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000958 v[0] = add;
959 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000960 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000961}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000962#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000963static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
964{
965 char **ptr = add_string_to_strings(strings, add);
966 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
967 return ptr;
968}
969#define add_string_to_strings(strings, add) \
970 xx_add_string_to_strings(__LINE__, strings, add)
971#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000972
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200973static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000974{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000975 char **v;
976
977 if (!strings)
978 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000979 v = strings;
980 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200981 free(*v);
982 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000983 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000984 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000985}
986
Denis Vlasenko76d50412008-06-10 16:19:39 +0000987
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000988/* Helpers for setting new $n and restoring them back
989 */
990typedef struct save_arg_t {
991 char *sv_argv0;
992 char **sv_g_argv;
993 int sv_g_argc;
994 smallint sv_g_malloced;
995} save_arg_t;
996
997static void save_and_replace_G_args(save_arg_t *sv, char **argv)
998{
999 int n;
1000
1001 sv->sv_argv0 = argv[0];
1002 sv->sv_g_argv = G.global_argv;
1003 sv->sv_g_argc = G.global_argc;
1004 sv->sv_g_malloced = G.global_args_malloced;
1005
1006 argv[0] = G.global_argv[0]; /* retain $0 */
1007 G.global_argv = argv;
1008 G.global_args_malloced = 0;
1009
1010 n = 1;
1011 while (*++argv)
1012 n++;
1013 G.global_argc = n;
1014}
1015
1016static void restore_G_args(save_arg_t *sv, char **argv)
1017{
1018 char **pp;
1019
1020 if (G.global_args_malloced) {
1021 /* someone ran "set -- arg1 arg2 ...", undo */
1022 pp = G.global_argv;
1023 while (*++pp) /* note: does not free $0 */
1024 free(*pp);
1025 free(G.global_argv);
1026 }
1027 argv[0] = sv->sv_argv0;
1028 G.global_argv = sv->sv_g_argv;
1029 G.global_argc = sv->sv_g_argc;
1030 G.global_args_malloced = sv->sv_g_malloced;
1031}
1032
1033
Denis Vlasenkod5762932009-03-31 11:22:57 +00001034/* Basic theory of signal handling in shell
1035 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001036 * This does not describe what hush does, rather, it is current understanding
1037 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001038 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1039 *
1040 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1041 * is finished or backgrounded. It is the same in interactive and
1042 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001043 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001044 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001045 * backgrounds (i.e. stops) or kills all members of currently running
1046 * pipe.
1047 *
1048 * Wait builtin in interruptible by signals for which user trap is set
1049 * or by SIGINT in interactive shell.
1050 *
1051 * Trap handlers will execute even within trap handlers. (right?)
1052 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001053 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001054 *
1055 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001056 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001057 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001058 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001059 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001060 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001061 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001062 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001063 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001064 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001065 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001066 *
1067 * SIGQUIT: ignore
1068 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001069 * SIGHUP (interactive):
1070 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001071 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001072 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1073 * that all pipe members are stopped. Try this in bash:
1074 * while :; do :; done - ^Z does not background it
1075 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001076 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001077 * of the command line, show prompt. NB: ^C does not send SIGINT
1078 * to interactive shell while shell is waiting for a pipe,
1079 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001080 * Example 1: this waits 5 sec, but does not execute ls:
1081 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1082 * Example 2: this does not wait and does not execute ls:
1083 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1084 * Example 3: this does not wait 5 sec, but executes ls:
1085 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001086 *
1087 * (What happens to signals which are IGN on shell start?)
1088 * (What happens with signal mask on shell start?)
1089 *
1090 * Implementation in hush
1091 * ======================
1092 * We use in-kernel pending signal mask to determine which signals were sent.
1093 * We block all signals which we don't want to take action immediately,
1094 * i.e. we block all signals which need to have special handling as described
1095 * above, and all signals which have traps set.
1096 * After each pipe execution, we extract any pending signals via sigtimedwait()
1097 * and act on them.
1098 *
1099 * unsigned non_DFL_mask: a mask of such "special" signals
1100 * sigset_t blocked_set: current blocked signal set
1101 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001102 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001103 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001104 * "trap 'cmd' SIGxxx":
1105 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001106 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001107 * unblock signals with special interactive handling
1108 * (child shell is not interactive),
1109 * unset all traps (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001110 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001111 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001112 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001113 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001114 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001115 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001116 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001117 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001118 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001119 * Standard says "When a subshell is entered, traps that are not being ignored
1120 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenko67f71862009-09-25 14:21:06 +02001121 * are set to "" (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001122 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001123enum {
1124 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001125 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001126 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001127 | (1 << SIGHUP)
1128 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001129 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001130#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001131 | (1 << SIGTTIN)
1132 | (1 << SIGTTOU)
1133 | (1 << SIGTSTP)
1134#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001135};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001136
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001137#if ENABLE_HUSH_FAST
1138static void SIGCHLD_handler(int sig UNUSED_PARAM)
1139{
1140 G.count_SIGCHLD++;
1141//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1142}
1143#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001144
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001145#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001146
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001147/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1148#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001149/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001150#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1151
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001152/* Restores tty foreground process group, and exits.
1153 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001154 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001155 * or called directly with -EXITCODE.
1156 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001157static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001158static void sigexit(int sig)
1159{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001160 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001161 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001162
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001163 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001164 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001165 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1166 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001167
1168 /* Not a signal, just exit */
1169 if (sig <= 0)
1170 _exit(- sig);
1171
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001172 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001173}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001174#else
1175
1176#define disable_restore_tty_pgrp_on_exit() ((void)0)
1177#define enable_restore_tty_pgrp_on_exit() ((void)0)
1178
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001179#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001180
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001181/* Restores tty foreground process group, and exits. */
1182static void hush_exit(int exitcode) NORETURN;
1183static void hush_exit(int exitcode)
1184{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001185 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1186 /* Prevent recursion:
1187 * trap "echo Hi; exit" EXIT; exit
1188 */
1189 char *argv[] = { NULL, G.traps[0], NULL };
1190 G.traps[0] = NULL;
1191 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001192 builtin_eval(argv);
1193 free(argv[1]);
1194 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001195
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001196#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001197 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001198 sigexit(- (exitcode & 0xff));
1199#else
1200 exit(exitcode);
1201#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001202}
1203
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001204static int check_and_run_traps(int sig)
1205{
1206 static const struct timespec zero_timespec = { 0, 0 };
1207 smalluint save_rcode;
1208 int last_sig = 0;
1209
1210 if (sig)
1211 goto jump_in;
1212 while (1) {
1213 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1214 if (sig <= 0)
1215 break;
1216 jump_in:
1217 last_sig = sig;
1218 if (G.traps && G.traps[sig]) {
1219 if (G.traps[sig][0]) {
1220 /* We have user-defined handler */
1221 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1222 save_rcode = G.last_exitcode;
1223 builtin_eval(argv);
1224 free(argv[1]);
1225 G.last_exitcode = save_rcode;
1226 } /* else: "" trap, ignoring signal */
1227 continue;
1228 }
1229 /* not a trap: special action */
1230 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001231#if ENABLE_HUSH_FAST
1232 case SIGCHLD:
1233 G.count_SIGCHLD++;
1234//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1235 break;
1236#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001237 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001238 /* Builtin was ^C'ed, make it look prettier: */
1239 bb_putchar('\n');
1240 G.flag_SIGINT = 1;
1241 break;
1242#if ENABLE_HUSH_JOB
1243 case SIGHUP: {
1244 struct pipe *job;
1245 /* bash is observed to signal whole process groups,
1246 * not individual processes */
1247 for (job = G.job_list; job; job = job->next) {
1248 if (job->pgrp <= 0)
1249 continue;
1250 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1251 if (kill(- job->pgrp, SIGHUP) == 0)
1252 kill(- job->pgrp, SIGCONT);
1253 }
1254 sigexit(SIGHUP);
1255 }
1256#endif
1257 default: /* ignored: */
1258 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1259 break;
1260 }
1261 }
1262 return last_sig;
1263}
1264
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001265
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001266static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001267{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001268 if (force || G.cwd == NULL) {
1269 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1270 * we must not try to free(bb_msg_unknown) */
1271 if (G.cwd == bb_msg_unknown)
1272 G.cwd = NULL;
1273 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1274 if (!G.cwd)
1275 G.cwd = bb_msg_unknown;
1276 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001277 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001278}
1279
Denis Vlasenko83506862007-11-23 13:11:42 +00001280
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001281/*
1282 * Shell and environment variable support
1283 */
1284static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001285{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001286 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001287 struct variable *cur;
1288 int len;
1289
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001290 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001291 pp = &G.top_var;
1292 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001293 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001294 return pp;
1295 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001296 }
1297 return NULL;
1298}
1299
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001300static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001301{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001302 struct variable **pp = get_ptr_to_local_var(name);
1303 if (pp)
1304 return *pp;
1305 return NULL;
1306}
1307
1308static const char *get_local_var_value(const char *name)
1309{
1310 struct variable **pp = get_ptr_to_local_var(name);
1311 if (pp)
1312 return strchr((*pp)->varstr, '=') + 1;
Denys Vlasenkodea47882009-10-09 15:40:49 +02001313 if (strcmp(name, "PPID") == 0)
1314 return utoa(G.root_ppid);
1315 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001316#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001317 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001318 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001319 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001320#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001321 return NULL;
1322}
1323
1324/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001325 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001326 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001327 * 0: do not change export flag
1328 * (if creating new variable, flag will be 0)
1329 * 1: set export flag and putenv the variable
1330 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001331 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001332 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001333#if !BB_MMU && ENABLE_HUSH_LOCAL
1334/* all params are used */
1335#elif BB_MMU && ENABLE_HUSH_LOCAL
1336#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1337 set_local_var(str, flg_export, local_lvl)
1338#elif BB_MMU && !ENABLE_HUSH_LOCAL
1339#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001340 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001341#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1342#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1343 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001344#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001345static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001346{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001347 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001348 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001349 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001350 int name_len;
1351
Denis Vlasenko950bd722009-04-21 11:23:56 +00001352 eq_sign = strchr(str, '=');
1353 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001354 free(str);
1355 return -1;
1356 }
1357
Denis Vlasenko950bd722009-04-21 11:23:56 +00001358 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001359 var_pp = &G.top_var;
1360 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001361 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001362 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001363 continue;
1364 }
1365 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001366 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001367#if !BB_MMU
1368 if (!flg_read_only)
1369#endif
1370 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001371 free(str);
1372 return -1;
1373 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001374 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001375 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1376 *eq_sign = '\0';
1377 unsetenv(str);
1378 *eq_sign = '=';
1379 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001380#if ENABLE_HUSH_LOCAL
1381 if (cur->func_nest_level < local_lvl) {
1382 /* New variable is declared as local,
1383 * and existing one is global, or local
1384 * from enclosing function.
1385 * Remove and save old one: */
1386 *var_pp = cur->next;
1387 cur->next = *G.shadowed_vars_pp;
1388 *G.shadowed_vars_pp = cur;
1389 /* bash 3.2.33(1) and exported vars:
1390 * # export z=z
1391 * # f() { local z=a; env | grep ^z; }
1392 * # f
1393 * z=a
1394 * # env | grep ^z
1395 * z=z
1396 */
1397 if (cur->flg_export)
1398 flg_export = 1;
1399 break;
1400 }
1401#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001402 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001403 free_and_exp:
1404 free(str);
1405 goto exp;
1406 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001407 if (cur->max_len != 0) {
1408 if (cur->max_len >= strlen(str)) {
1409 /* This one is from startup env, reuse space */
1410 strcpy(cur->varstr, str);
1411 goto free_and_exp;
1412 }
1413 } else {
1414 /* max_len == 0 signifies "malloced" var, which we can
1415 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001416 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001417 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001418 cur->max_len = 0;
1419 goto set_str_and_exp;
1420 }
1421
Denys Vlasenko295fef82009-06-03 12:47:26 +02001422 /* Not found - create new variable struct */
1423 cur = xzalloc(sizeof(*cur));
1424#if ENABLE_HUSH_LOCAL
1425 cur->func_nest_level = local_lvl;
1426#endif
1427 cur->next = *var_pp;
1428 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001429
1430 set_str_and_exp:
1431 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001432#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001433 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001434#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001435 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001436 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001437 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001438 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1439 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001440 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001441 if (flg_export == -1) {
1442 cur->flg_export = 0;
1443 /* unsetenv was already done */
1444 } else {
1445 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1446 return putenv(cur->varstr);
1447 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001448 }
1449 return 0;
1450}
1451
Denys Vlasenko6db47842009-09-05 20:15:17 +02001452/* Used at startup and after each cd */
1453static void set_pwd_var(int exp)
1454{
1455 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1456 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1457}
1458
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001459static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001460{
1461 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001462 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001463
1464 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001465 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001466 var_pp = &G.top_var;
1467 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001468 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1469 if (cur->flg_read_only) {
1470 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001471 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001472 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001473 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001474 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1475 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001476 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1477 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001478 if (!cur->max_len)
1479 free(cur->varstr);
1480 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001481 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001482 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001483 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001484 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001485 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001486}
1487
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001488static int unset_local_var(const char *name)
1489{
1490 return unset_local_var_len(name, strlen(name));
1491}
1492
1493static void unset_vars(char **strings)
1494{
1495 char **v;
1496
1497 if (!strings)
1498 return;
1499 v = strings;
1500 while (*v) {
1501 const char *eq = strchrnul(*v, '=');
1502 unset_local_var_len(*v, (int)(eq - *v));
1503 v++;
1504 }
1505 free(strings);
1506}
1507
Mike Frysinger98c52642009-04-02 10:02:37 +00001508#if ENABLE_SH_MATH_SUPPORT
1509#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1510#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1511static char *endofname(const char *name)
1512{
1513 char *p;
1514
1515 p = (char *) name;
1516 if (!is_name(*p))
1517 return p;
1518 while (*++p) {
1519 if (!is_in_name(*p))
1520 break;
1521 }
1522 return p;
1523}
1524
1525static void arith_set_local_var(const char *name, const char *val, int flags)
1526{
1527 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001528 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001529 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001530}
1531#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001532
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001533
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001534/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001535 * Helpers for "var1=val1 var2=val2 cmd" feature
1536 */
1537static void add_vars(struct variable *var)
1538{
1539 struct variable *next;
1540
1541 while (var) {
1542 next = var->next;
1543 var->next = G.top_var;
1544 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001545 if (var->flg_export) {
1546 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001547 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001548 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001549 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001550 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001551 var = next;
1552 }
1553}
1554
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001555static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001556{
1557 char **s;
1558 struct variable *old = NULL;
1559
1560 if (!strings)
1561 return old;
1562 s = strings;
1563 while (*s) {
1564 struct variable *var_p;
1565 struct variable **var_pp;
1566 char *eq;
1567
1568 eq = strchr(*s, '=');
1569 if (eq) {
1570 *eq = '\0';
1571 var_pp = get_ptr_to_local_var(*s);
1572 *eq = '=';
1573 if (var_pp) {
1574 /* Remove variable from global linked list */
1575 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001576 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001577 *var_pp = var_p->next;
1578 /* Add it to returned list */
1579 var_p->next = old;
1580 old = var_p;
1581 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001582 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001583 }
1584 s++;
1585 }
1586 return old;
1587}
1588
1589
1590/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001591 * in_str support
1592 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001593static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001594{
1595 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001596 if (ch != '\0')
1597 return ch;
1598 i->p--;
1599 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001600}
1601
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001602static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001603{
1604 return *i->p;
1605}
1606
1607#if ENABLE_HUSH_INTERACTIVE
1608
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001609static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001610{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001611 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001612 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001613 if (G.PS1 == NULL)
1614 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001615 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001616 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001617 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001618 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001619 if (G.PS2 == NULL)
1620 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001621}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001622
1623static const char* setup_prompt_string(int promptmode)
1624{
1625 const char *prompt_str;
1626 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001627 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1628 /* Set up the prompt */
1629 if (promptmode == 0) { /* PS1 */
1630 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001631 /* bash uses $PWD value, even if it is set by user.
1632 * It uses current dir only if PWD is unset.
1633 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001634 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001635 prompt_str = G.PS1;
1636 } else
1637 prompt_str = G.PS2;
1638 } else
1639 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001640 debug_printf("result '%s'\n", prompt_str);
1641 return prompt_str;
1642}
1643
1644static void get_user_input(struct in_str *i)
1645{
1646 int r;
1647 const char *prompt_str;
1648
1649 prompt_str = setup_prompt_string(i->promptmode);
1650#if ENABLE_FEATURE_EDITING
1651 /* Enable command line editing only while a command line
1652 * is actually being read */
1653 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001654 G.flag_SIGINT = 0;
1655 /* buglet: SIGINT will not make new prompt to appear _at once_,
1656 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001657 r = read_line_input(prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001658 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001659 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001660 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001661 i->eof_flag = (r < 0);
1662 if (i->eof_flag) { /* EOF/error detected */
1663 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1664 G.user_input_buf[1] = '\0';
1665 }
1666#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001667 do {
1668 G.flag_SIGINT = 0;
1669 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001670 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001671 G.user_input_buf[0] = r = fgetc(i->file);
1672 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001673//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001674 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001675 i->eof_flag = (r == EOF);
1676#endif
1677 i->p = G.user_input_buf;
1678}
1679
1680#endif /* INTERACTIVE */
1681
1682/* This is the magic location that prints prompts
1683 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001684static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685{
1686 int ch;
1687
1688 /* If there is data waiting, eat it up */
1689 if (i->p && *i->p) {
1690#if ENABLE_HUSH_INTERACTIVE
1691 take_cached:
1692#endif
1693 ch = *i->p++;
1694 if (i->eof_flag && !*i->p)
1695 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001696 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001697 } else {
1698 /* need to double check i->file because we might be doing something
1699 * more complicated by now, like sourcing or substituting. */
1700#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001701 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001702 do {
1703 get_user_input(i);
1704 } while (!*i->p); /* need non-empty line */
1705 i->promptmode = 1; /* PS2 */
1706 i->promptme = 0;
1707 goto take_cached;
1708 }
1709#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001710 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001711 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001712 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001713#if ENABLE_HUSH_INTERACTIVE
1714 if (ch == '\n')
1715 i->promptme = 1;
1716#endif
1717 return ch;
1718}
1719
Denis Vlasenko913a2012009-04-05 22:17:04 +00001720/* All callers guarantee this routine will never
1721 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001722 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001723static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001724{
1725 int ch;
1726 if (i->p && *i->p) {
1727 if (i->eof_flag && !i->p[1])
1728 return EOF;
1729 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001730 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001731 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001732 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001733 i->eof_flag = (ch == EOF);
1734 i->peek_buf[0] = ch;
1735 i->peek_buf[1] = '\0';
1736 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001737 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001738 return ch;
1739}
1740
1741static void setup_file_in_str(struct in_str *i, FILE *f)
1742{
1743 i->peek = file_peek;
1744 i->get = file_get;
1745#if ENABLE_HUSH_INTERACTIVE
1746 i->promptme = 1;
1747 i->promptmode = 0; /* PS1 */
1748#endif
1749 i->file = f;
1750 i->p = NULL;
1751}
1752
1753static void setup_string_in_str(struct in_str *i, const char *s)
1754{
1755 i->peek = static_peek;
1756 i->get = static_get;
1757#if ENABLE_HUSH_INTERACTIVE
1758 i->promptme = 1;
1759 i->promptmode = 0; /* PS1 */
1760#endif
1761 i->p = s;
1762 i->eof_flag = 0;
1763}
1764
1765
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001766/*
1767 * o_string support
1768 */
1769#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001770
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001771static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001772{
1773 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001774 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001775 if (o->data)
1776 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001777}
1778
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001779static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001780{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001781 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001782 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001783}
1784
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001785static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1786{
1787 free(o->data);
1788}
1789
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001790static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001791{
1792 if (o->length + len > o->maxlen) {
1793 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1794 o->data = xrealloc(o->data, 1 + o->maxlen);
1795 }
1796}
1797
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001798static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001799{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001800 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1801 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001802 o->data[o->length] = ch;
1803 o->length++;
1804 o->data[o->length] = '\0';
1805}
1806
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001807static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001808{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001809 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001810 memcpy(&o->data[o->length], str, len);
1811 o->length += len;
1812 o->data[o->length] = '\0';
1813}
1814
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001815#if !BB_MMU
1816static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001817{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001818 o_addblock(o, str, strlen(str));
1819}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001820static void nommu_addchr(o_string *o, int ch)
1821{
1822 if (o)
1823 o_addchr(o, ch);
1824}
1825#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001826# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001827#endif
1828
1829static void o_addstr_with_NUL(o_string *o, const char *str)
1830{
1831 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001832}
1833
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001834static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001835{
1836 while (len) {
1837 o_addchr(o, *str);
1838 if (*str++ == '\\'
1839 && (*str != '*' && *str != '?' && *str != '[')
1840 ) {
1841 o_addchr(o, '\\');
1842 }
1843 len--;
1844 }
1845}
1846
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001847#undef HUSH_BRACE_EXP
1848/*
1849 * HUSH_BRACE_EXP code needs corresponding quoting on variable expansion side.
1850 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
1851 * Apparently, on unquoted $v bash still does globbing
1852 * ("v='*.txt'; echo $v" prints all .txt files),
1853 * but NOT brace expansion! Thus, there should be TWO independent
1854 * quoting mechanisms on $v expansion side: one protects
1855 * $v from brace expansion, and other additionally protects "$v" against globbing.
1856 * We have only second one.
1857 */
1858
1859#ifdef HUSH_BRACE_EXP
1860# define MAYBE_BRACES "{}"
1861#else
1862# define MAYBE_BRACES ""
1863#endif
1864
Eric Andersen25f27032001-04-26 23:22:31 +00001865/* My analysis of quoting semantics tells me that state information
1866 * is associated with a destination, not a source.
1867 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001868static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001869{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001870 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001871 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001872 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001873 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001874 o_grow_by(o, sz);
1875 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001876 o->data[o->length] = '\\';
1877 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001878 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001879 o->data[o->length] = ch;
1880 o->length++;
1881 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001882}
1883
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001884static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001885{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001886 int sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001887 if (o->o_escape && strchr("*?[\\" MAYBE_BRACES, ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001888 sz++;
1889 o->data[o->length] = '\\';
1890 o->length++;
1891 }
1892 o_grow_by(o, sz);
1893 o->data[o->length] = ch;
1894 o->length++;
1895 o->data[o->length] = '\0';
1896}
1897
1898static void o_addQstr(o_string *o, const char *str, int len)
1899{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001900 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001901 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001902 return;
1903 }
1904 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001905 char ch;
1906 int sz;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001907 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001908 if (ordinary_cnt > len) /* paranoia */
1909 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001910 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001911 if (ordinary_cnt == len)
1912 return;
1913 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001914 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001915
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001916 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001917 sz = 1;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01001918 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001919 sz++;
1920 o->data[o->length] = '\\';
1921 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001922 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001923 o_grow_by(o, sz);
1924 o->data[o->length] = ch;
1925 o->length++;
1926 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001927 }
1928}
1929
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001930/* A special kind of o_string for $VAR and `cmd` expansion.
1931 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001932 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001933 * list[i] contains an INDEX (int!) into this string data.
1934 * It means that if list[] needs to grow, data needs to be moved higher up
1935 * but list[i]'s need not be modified.
1936 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001937 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001938 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1939 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001940#if DEBUG_EXPAND || DEBUG_GLOB
1941static void debug_print_list(const char *prefix, o_string *o, int n)
1942{
1943 char **list = (char**)o->data;
1944 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1945 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001946
1947 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001948 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1949 prefix, list, n, string_start, o->length, o->maxlen);
1950 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001951 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001952 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1953 o->data + (int)list[i] + string_start,
1954 o->data + (int)list[i] + string_start);
1955 i++;
1956 }
1957 if (n) {
1958 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001959 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001960 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001961 }
1962}
1963#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001964# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001965#endif
1966
1967/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1968 * in list[n] so that it points past last stored byte so far.
1969 * It returns n+1. */
1970static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001971{
1972 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001973 int string_start;
1974 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001975
1976 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001977 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1978 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001979 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001980 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001981 /* list[n] points to string_start, make space for 16 more pointers */
1982 o->maxlen += 0x10 * sizeof(list[0]);
1983 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001984 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001985 memmove(list + n + 0x10, list + n, string_len);
1986 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001987 } else {
1988 debug_printf_list("list[%d]=%d string_start=%d\n",
1989 n, string_len, string_start);
1990 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001991 } else {
1992 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001993 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1994 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001995 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1996 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001997 o->has_empty_slot = 0;
1998 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001999 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002000 return n + 1;
2001}
2002
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002003/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002004static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002005{
2006 char **list = (char**)o->data;
2007 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2008
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002009 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002010}
2011
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002012#ifdef HUSH_BRACE_EXP
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002013/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2014 * first, it processes even {a} (no commas), second,
2015 * I didn't manage to make it return strings when they don't match
Denys Vlasenko160746b2009-11-16 05:51:18 +01002016 * existing files. Need to re-implement it.
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002017 */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002018
2019/* Helper */
2020static int glob_needed(const char *s)
2021{
2022 while (*s) {
2023 if (*s == '\\') {
2024 if (!s[1])
2025 return 0;
2026 s += 2;
2027 continue;
2028 }
2029 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2030 return 1;
2031 s++;
2032 }
2033 return 0;
2034}
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002035/* Return pointer to next closing brace or to comma */
2036static const char *next_brace_sub(const char *cp)
2037{
2038 unsigned depth = 0;
2039 cp++;
2040 while (*cp != '\0') {
2041 if (*cp == '\\') {
2042 if (*++cp == '\0')
2043 break;
2044 cp++;
2045 continue;
2046 }
2047 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2048 break;
2049 if (*cp++ == '{') /*}*/
2050 depth++;
2051 }
2052
2053 return *cp != '\0' ? cp : NULL;
2054}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002055/* Recursive brace globber. Note: may garble pattern[]. */
2056static int glob_brace(char *pattern, o_string *o, int n)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002057{
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002058 char *new_pattern_buf;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002059 const char *begin;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002060 const char *next;
2061 const char *rest;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002062 const char *p;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002063 size_t rest_len;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002064
2065 debug_printf_glob("glob_brace('%s')\n", pattern);
2066
2067 begin = pattern;
2068 while (1) {
2069 if (*begin == '\0')
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002070 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002071 if (*begin == '{') /*}*/ {
2072 /* Find the first sub-pattern and at the same time
2073 * find the rest after the closing brace */
2074 next = next_brace_sub(begin);
2075 if (next == NULL) {
2076 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002077 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002078 }
2079 /*{*/ if (*next == '}') {
2080 /* "{abc}" with no commas - illegal
2081 * brace expr, disregard and skip it */
2082 begin = next + 1;
2083 continue;
2084 }
2085 break;
2086 }
2087 if (*begin == '\\' && begin[1] != '\0')
2088 begin++;
2089 begin++;
2090 }
2091 debug_printf_glob("begin:%s\n", begin);
2092 debug_printf_glob("next:%s\n", next);
2093
2094 /* Now find the end of the whole brace expression */
2095 rest = next;
2096 /*{*/ while (*rest != '}') {
2097 rest = next_brace_sub(rest);
2098 if (rest == NULL) {
2099 /* An illegal expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002100 goto simple_glob;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002101 }
2102 debug_printf_glob("rest:%s\n", rest);
2103 }
2104 rest_len = strlen(++rest) + 1;
2105
2106 /* We are sure the brace expression is well-formed */
2107
2108 /* Allocate working buffer large enough for our work */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002109 new_pattern_buf = xmalloc(strlen(pattern));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002110
2111 /* We have a brace expression. BEGIN points to the opening {,
2112 * NEXT points past the terminator of the first element, and REST
2113 * points past the final }. We will accumulate result names from
2114 * recursive runs for each brace alternative in the buffer using
2115 * GLOB_APPEND. */
2116
2117 p = begin + 1;
2118 while (1) {
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002119 /* Construct the new glob expression */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002120 memcpy(
2121 mempcpy(
2122 mempcpy(new_pattern_buf,
2123 /* We know the prefix for all sub-patterns */
2124 pattern, begin - pattern),
2125 p, next - p),
2126 rest, rest_len);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002127
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002128 /* Note: glob_brace() may garble new_pattern_buf[].
2129 * That's why we re-copy prefix every time (1st memcpy above).
2130 */
2131 n = glob_brace(new_pattern_buf, o, n);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002132 /*{*/ if (*next == '}') {
2133 /* We saw the last entry */
2134 break;
2135 }
2136 p = next + 1;
2137 next = next_brace_sub(next);
2138 }
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002139 free(new_pattern_buf);
2140 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002141
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002142 simple_glob:
2143 {
2144 int gr;
2145 glob_t globdata;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002146
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002147 memset(&globdata, 0, sizeof(globdata));
2148 gr = glob(pattern, 0, NULL, &globdata);
2149 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2150 if (gr != 0) {
2151 if (gr == GLOB_NOMATCH) {
2152 globfree(&globdata);
2153 /* NB: garbles parameter */
2154 unbackslash(pattern);
2155 o_addstr_with_NUL(o, pattern);
2156 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2157 return o_save_ptr_helper(o, n);
2158 }
2159 if (gr == GLOB_NOSPACE)
2160 bb_error_msg_and_die(bb_msg_memory_exhausted);
2161 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2162 * but we didn't specify it. Paranoia again. */
2163 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2164 }
2165 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2166 char **argv = globdata.gl_pathv;
2167 while (1) {
2168 o_addstr_with_NUL(o, *argv);
2169 n = o_save_ptr_helper(o, n);
2170 argv++;
2171 if (!*argv)
2172 break;
2173 }
2174 }
2175 globfree(&globdata);
2176 }
2177 return n;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002178}
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002179/* Performs globbing on last list[],
2180 * saving each result as a new list[].
2181 */
2182static int o_glob(o_string *o, int n)
2183{
2184 char *pattern, *copy;
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002185
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002186 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
2187 if (!o->data)
2188 return o_save_ptr_helper(o, n);
2189 pattern = o->data + o_get_last_ptr(o, n);
2190 debug_printf_glob("glob pattern '%s'\n", pattern);
2191 if (!glob_needed(pattern)) {
2192 /* unbackslash last string in o in place, fix length */
2193 o->length = unbackslash(pattern) - o->data;
2194 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2195 return o_save_ptr_helper(o, n);
2196 }
2197
2198 copy = xstrdup(pattern);
2199 /* "forget" pattern in o */
2200 o->length = pattern - o->data;
2201 n = glob_brace(copy, o, n);
2202 free(copy);
2203 if (DEBUG_GLOB)
2204 debug_print_list("o_glob returning", o, n);
2205 return n;
2206}
2207
2208#else
2209
2210/* Helper */
2211static int glob_needed(const char *s)
2212{
2213 while (*s) {
2214 if (*s == '\\') {
2215 if (!s[1])
2216 return 0;
2217 s += 2;
2218 continue;
2219 }
2220 if (*s == '*' || *s == '[' || *s == '?')
2221 return 1;
2222 s++;
2223 }
2224 return 0;
2225}
2226/* Performs globbing on last list[],
2227 * saving each result as a new list[].
2228 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002229static int o_glob(o_string *o, int n)
2230{
2231 glob_t globdata;
2232 int gr;
2233 char *pattern;
2234
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002235 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002236 if (!o->data)
2237 return o_save_ptr_helper(o, n);
2238 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002239 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002240 if (!glob_needed(pattern)) {
2241 literal:
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002242 /* unbackslash last string in o in place, fix length */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002243 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002244 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002245 return o_save_ptr_helper(o, n);
2246 }
2247
2248 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002249 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2250 * If we glob "*.\*" and don't find anything, we need
2251 * to fall back to using literal "*.*", but GLOB_NOCHECK
2252 * will return "*.\*"!
2253 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002254 gr = glob(pattern, 0, NULL, &globdata);
2255 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002256 if (gr != 0) {
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002257 if (gr == GLOB_NOMATCH) {
2258 globfree(&globdata);
2259 goto literal;
2260 }
2261 if (gr == GLOB_NOSPACE)
2262 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002263 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2264 * but we didn't specify it. Paranoia again. */
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002265 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002266 }
2267 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2268 char **argv = globdata.gl_pathv;
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002269 /* "forget" pattern in o */
2270 o->length = pattern - o->data;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002271 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002272 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002273 n = o_save_ptr_helper(o, n);
2274 argv++;
2275 if (!*argv)
2276 break;
2277 }
2278 }
2279 globfree(&globdata);
2280 if (DEBUG_GLOB)
2281 debug_print_list("o_glob returning", o, n);
2282 return n;
2283}
2284
Denys Vlasenkof3e28182009-11-17 03:35:31 +01002285#endif
2286
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002287/* If o->o_glob == 1, glob the string so far remembered.
2288 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002289static int o_save_ptr(o_string *o, int n)
2290{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002291 if (o->o_glob) { /* if globbing is requested */
2292 /* If o->has_empty_slot, list[n] was already globbed
2293 * (if it was requested back then when it was filled)
2294 * so don't do that again! */
2295 if (!o->has_empty_slot)
2296 return o_glob(o, n); /* o_save_ptr_helper is inside */
2297 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002298 return o_save_ptr_helper(o, n);
2299}
2300
2301/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002302static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002303{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002304 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002305 int string_start;
2306
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002307 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2308 if (DEBUG_EXPAND)
2309 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002310 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002311 list = (char**)o->data;
2312 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2313 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002314 while (n) {
2315 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002316 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002317 }
2318 return list;
2319}
2320
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002321
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002322/* Expansion can recurse */
2323#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002324static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002325#endif
2326static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002327#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002328#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002329 parse_stream_dquoted(dest, input, dquote_end)
2330#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002331static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002332 o_string *dest,
2333 struct in_str *input,
2334 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002335
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336/* expand_strvec_to_strvec() takes a list of strings, expands
2337 * all variable references within and returns a pointer to
2338 * a list of expanded strings, possibly with larger number
2339 * of strings. (Think VAR="a b"; echo $VAR).
2340 * This new list is allocated as a single malloc block.
2341 * NULL-terminated list of char* pointers is at the beginning of it,
2342 * followed by strings themself.
2343 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002344
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345/* Store given string, finalizing the word and starting new one whenever
2346 * we encounter IFS char(s). This is used for expanding variable values.
2347 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2348static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002349{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002350 while (1) {
2351 int word_len = strcspn(str, G.ifs);
2352 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002353 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002354 o_addQstr(output, str, word_len);
2355 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002356 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002357 str += word_len;
2358 }
2359 if (!*str) /* EOL - do not finalize word */
2360 break;
2361 o_addchr(output, '\0');
2362 debug_print_list("expand_on_ifs", output, n);
2363 n = o_save_ptr(output, n);
2364 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002365 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002366 debug_print_list("expand_on_ifs[1]", output, n);
2367 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002368}
2369
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002370/* Helper to expand $((...)) and heredoc body. These act as if
2371 * they are in double quotes, with the exception that they are not :).
2372 * Just the rules are similar: "expand only $var and `cmd`"
2373 *
2374 * Returns malloced string.
2375 * As an optimization, we return NULL if expansion is not needed.
2376 */
2377static char *expand_pseudo_dquoted(const char *str)
2378{
2379 char *exp_str;
2380 struct in_str input;
2381 o_string dest = NULL_O_STRING;
2382
2383 if (strchr(str, '$') == NULL
2384#if ENABLE_HUSH_TICK
2385 && strchr(str, '`') == NULL
2386#endif
2387 ) {
2388 return NULL;
2389 }
2390
2391 /* We need to expand. Example:
2392 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2393 */
2394 setup_string_in_str(&input, str);
2395 parse_stream_dquoted(NULL, &dest, &input, EOF);
2396 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2397 exp_str = expand_string_to_string(dest.data);
2398 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2399 o_free_unsafe(&dest);
2400 return exp_str;
2401}
2402
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002403/* Expand all variable references in given string, adding words to list[]
2404 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2405 * to be filled). This routine is extremely tricky: has to deal with
2406 * variables/parameters with whitespace, $* and $@, and constructs like
2407 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002408static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002409{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002410 /* or_mask is either 0 (normal case) or 0x80 -
2411 * expansion of right-hand side of assignment == 1-element expand.
2412 * It will also do no globbing, and thus we must not backslash-quote!
2413 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002414 char ored_ch;
2415 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002416
2417 ored_ch = 0;
2418
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002419 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002420 debug_print_list("expand_vars_to_list", output, n);
2421 n = o_save_ptr(output, n);
2422 debug_print_list("expand_vars_to_list[0]", output, n);
2423
2424 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002425 char first_ch;
2426 int i;
2427 char *dyn_val = NULL;
2428 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002429#if ENABLE_HUSH_TICK
2430 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002431#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002432#if ENABLE_SH_MATH_SUPPORT
2433 char arith_buf[sizeof(arith_t)*3 + 2];
2434#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002435 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002436 debug_print_list("expand_vars_to_list[1]", output, n);
2437 arg = ++p;
2438 p = strchr(p, SPECIAL_VAR_SYMBOL);
2439
2440 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2441 /* "$@" is special. Even if quoted, it can still
2442 * expand to nothing (not even an empty string) */
2443 if ((first_ch & 0x7f) != '@')
2444 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002445
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002446 switch (first_ch & 0x7f) {
2447 /* Highest bit in first_ch indicates that var is double-quoted */
2448 case '$': /* pid */
2449 val = utoa(G.root_pid);
2450 break;
2451 case '!': /* bg pid */
2452 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2453 break;
2454 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002455 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002456 break;
2457 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002458 if (arg[1] != SPECIAL_VAR_SYMBOL)
2459 /* actually, it's a ${#var} */
2460 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002461 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2462 break;
2463 case '*':
2464 case '@':
2465 i = 1;
2466 if (!G.global_argv[i])
2467 break;
2468 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2469 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002470 smallint sv = output->o_escape;
2471 /* unquoted var's contents should be globbed, so don't escape */
2472 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002473 while (G.global_argv[i]) {
2474 n = expand_on_ifs(output, n, G.global_argv[i]);
2475 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2476 if (G.global_argv[i++][0] && G.global_argv[i]) {
2477 /* this argv[] is not empty and not last:
2478 * put terminating NUL, start new word */
2479 o_addchr(output, '\0');
2480 debug_print_list("expand_vars_to_list[2]", output, n);
2481 n = o_save_ptr(output, n);
2482 debug_print_list("expand_vars_to_list[3]", output, n);
2483 }
2484 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002485 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002486 } else
2487 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2488 * and in this case should treat it like '$*' - see 'else...' below */
2489 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2490 while (1) {
2491 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2492 if (++i >= G.global_argc)
2493 break;
2494 o_addchr(output, '\0');
2495 debug_print_list("expand_vars_to_list[4]", output, n);
2496 n = o_save_ptr(output, n);
2497 }
2498 } else { /* quoted $*: add as one word */
2499 while (1) {
2500 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2501 if (!G.global_argv[++i])
2502 break;
2503 if (G.ifs[0])
2504 o_addchr(output, G.ifs[0]);
2505 }
2506 }
2507 break;
2508 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2509 /* "Empty variable", used to make "" etc to not disappear */
2510 arg++;
2511 ored_ch = 0x80;
2512 break;
2513#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002514 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002515 *p = '\0';
2516 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002517 /* Can't just stuff it into output o_string,
2518 * expanded result may need to be globbed
2519 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002520 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002521 G.last_exitcode = process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002522 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2523 val = subst_result.data;
2524 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002525#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002526#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002527 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002528 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002529 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002530 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002531 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002532
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002533 arg++; /* skip '+' */
2534 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002535 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002536
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002537 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002538 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002539 hooks.setvar = arith_set_local_var;
2540 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002541 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2542 free(exp_str);
2543
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002544 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002545 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002546 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002547 case -3:
2548 msg = "exponent less than 0";
2549 break;
2550 case -2:
2551 msg = "divide by 0";
2552 break;
2553 case -5:
2554 msg = "expression recursion loop detected";
2555 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002556 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002557 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002558 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002559 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002560 sprintf(arith_buf, arith_t_fmt, res);
2561 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002562 break;
2563 }
2564#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002565 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002566 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002567 bool exp_len = false;
2568 bool exp_null = false;
2569 char *var = arg;
2570 char exp_save = exp_save; /* for compiler */
2571 char exp_op = exp_op; /* for compiler */
2572 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002573 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002574
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002575 *p = '\0';
2576 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002577
2578 /* prepare for expansions */
2579 if (var[0] == '#') {
2580 /* handle length expansion ${#var} */
2581 exp_len = true;
2582 ++var;
2583 } else {
2584 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002585 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002586 if (!var[exp_off])
2587 exp_off = 0;
2588 if (exp_off) {
2589 exp_save = var[exp_off];
2590 exp_null = exp_save == ':';
2591 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002592 if (exp_null)
2593 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002594 exp_op = *exp_word++;
2595 var[exp_off] = '\0';
2596 }
2597 }
2598
2599 /* lookup the variable in question */
2600 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002601 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002602 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002603 if (i < G.global_argc)
2604 val = G.global_argv[i];
2605 /* else val remains NULL: $N with too big N */
2606 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002607 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002608
2609 /* handle any expansions */
2610 if (exp_len) {
2611 debug_printf_expand("expand: length of '%s' = ", val);
2612 val = utoa(val ? strlen(val) : 0);
2613 debug_printf_expand("%s\n", val);
2614 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002615 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002616 if (val) {
2617 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002618 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002619 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002620 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002621 if (exp_op == *exp_word) /* ## or %% */
2622 ++exp_word;
2623 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002624 loc = scan(dyn_val, exp_word, match_at_left);
2625 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002626 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002627 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002628 *loc = '\0';
2629 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002630 } else {
2631 /* we need to do an expansion */
2632 int exp_test = (!val || (exp_null && !val[0]));
2633 if (exp_op == '+')
2634 exp_test = !exp_test;
2635 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2636 exp_null ? "true" : "false", exp_test);
2637 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002638 if (exp_op == '?') {
2639//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002640 /* ${var?[error_msg_if_unset]} */
2641 /* ${var:?[error_msg_if_unset_or_null]} */
2642 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002643 die_if_script("%s: %s",
2644 var,
2645 exp_word[0] ? exp_word : "parameter null or not set"
2646 );
2647 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002648 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002649 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002650
Mike Frysingera4f331d2009-04-07 06:03:22 +00002651 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002652 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002653 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002654 /* mimic bash message */
2655 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002656 val = NULL;
2657 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002658 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002659 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002660 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002661 }
2662 }
2663 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002664
Mike Frysinger6379bb42009-03-28 18:55:03 +00002665 var[exp_off] = exp_save;
2666 }
2667
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002668 arg[0] = first_ch;
2669#if ENABLE_HUSH_TICK
2670 store_val:
2671#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002672 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002673 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002674 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002675 /* unquoted var's contents should be globbed, so don't escape */
2676 smallint sv = output->o_escape;
2677 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002678 n = expand_on_ifs(output, n, val);
2679 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002680 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002681 }
2682 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002683 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002684 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002685 } /* default: */
2686 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002687
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002688 if (val) {
2689 o_addQstr(output, val, strlen(val));
2690 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002691 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002692 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002693 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002694 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002695
2696#if ENABLE_HUSH_TICK
2697 o_free(&subst_result);
2698#endif
2699 arg = ++p;
2700 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2701
2702 if (arg[0]) {
2703 debug_print_list("expand_vars_to_list[a]", output, n);
2704 /* this part is literal, and it was already pre-quoted
2705 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002706 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002707 debug_print_list("expand_vars_to_list[b]", output, n);
2708 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2709 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2710 ) {
2711 n--;
2712 /* allow to reuse list[n] later without re-growth */
2713 output->has_empty_slot = 1;
2714 } else {
2715 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002716 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002717 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002718}
2719
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002720static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002721{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002722 int n;
2723 char **list;
2724 char **v;
2725 o_string output = NULL_O_STRING;
2726
2727 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002728 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002729 /* (unquoted $var will temporarily switch it off) */
2730 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002731 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002732
2733 n = 0;
2734 v = argv;
2735 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002736 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002737 v++;
2738 }
2739 debug_print_list("expand_variables", &output, n);
2740
2741 /* output.data (malloced in one block) gets returned in "list" */
2742 list = o_finalize_list(&output, n);
2743 debug_print_strings("expand_variables[1]", list);
2744 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002745}
2746
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002747static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002748{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002749 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002750}
2751
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002752#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002753static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2754{
2755 return expand_variables(argv, 0x80);
2756}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002757#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002758
2759#ifdef CMD_SINGLEWORD_NOGLOB_COND
2760static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2761{
2762 int n;
2763 char **list;
2764 char **v;
2765 o_string output = NULL_O_STRING;
2766
2767 n = 0;
2768 v = argv;
2769 while (*v) {
2770 int is_var = is_well_formed_var_name(*v, '=');
2771 /* is_var * 0x80: singleword expansion for vars */
2772 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2773
2774 /* Subtle! expand_vars_to_list did not glob last word yet.
2775 * It does this only when fed with further data.
2776 * Therefore we set globbing flags AFTER it, not before:
2777 */
2778
2779 /* if it is not recognizably abc=...; then: */
2780 output.o_escape = !is_var; /* protect against globbing for "$var" */
2781 /* (unquoted $var will temporarily switch it off) */
2782 output.o_glob = !is_var; /* and indeed do globbing */
2783 v++;
2784 }
2785 debug_print_list("expand_cond", &output, n);
2786
2787 /* output.data (malloced in one block) gets returned in "list" */
2788 list = o_finalize_list(&output, n);
2789 debug_print_strings("expand_cond[1]", list);
2790 return list;
2791}
2792#endif
2793
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002794/* Used for expansion of right hand of assignments */
2795/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2796 * "v=/bin/c*" */
2797static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002798{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002799 char *argv[2], **list;
2800
2801 argv[0] = (char*)str;
2802 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002803 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002804 if (HUSH_DEBUG)
2805 if (!list[0] || list[1])
2806 bb_error_msg_and_die("BUG in varexp2");
2807 /* actually, just move string 2*sizeof(char*) bytes back */
2808 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002809 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002810 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2811 return (char*)list;
2812}
2813
2814/* Used for "eval" builtin */
2815static char* expand_strvec_to_string(char **argv)
2816{
2817 char **list;
2818
2819 list = expand_variables(argv, 0x80);
2820 /* Convert all NULs to spaces */
2821 if (list[0]) {
2822 int n = 1;
2823 while (list[n]) {
2824 if (HUSH_DEBUG)
2825 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2826 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002827 /* bash uses ' ' regardless of $IFS contents */
2828 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002829 n++;
2830 }
2831 }
2832 overlapping_strcpy((char*)list, list[0]);
2833 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2834 return (char*)list;
2835}
2836
2837static char **expand_assignments(char **argv, int count)
2838{
2839 int i;
2840 char **p = NULL;
2841 /* Expand assignments into one string each */
2842 for (i = 0; i < count; i++) {
2843 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2844 }
2845 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002846}
2847
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002848
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002849#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002850/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002851void re_execute_shell(char ***to_free, const char *s,
2852 char *g_argv0, char **g_argv,
2853 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002854
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002855static void reset_traps_to_defaults(void)
2856{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002857 /* This function is always called in a child shell
2858 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002859 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002860 unsigned sig;
2861 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002862
Denys Vlasenko67f71862009-09-25 14:21:06 +02002863 /* Child shells are not interactive.
2864 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2865 * Testcase: (while :; do :; done) + ^Z should background.
2866 * Same goes for SIGTERM, SIGHUP, SIGINT.
2867 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002868 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002869 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002870
Denys Vlasenko67f71862009-09-25 14:21:06 +02002871 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2872 * Stupid. It can be done with *single* &= op, but we can't use
2873 * the fact that G.blocked_set is implemented as a bitmask
2874 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002875 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2876 sig = 1;
2877 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002878 if (mask & 1) {
2879 /* Careful. Only if no trap or trap is not "" */
2880 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2881 sigdelset(&G.blocked_set, sig);
2882 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002883 mask >>= 1;
2884 if (!mask)
2885 break;
2886 sig++;
2887 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002888 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002889 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002890
2891 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002892 mask = G.non_DFL_mask;
2893 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002894 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002895 continue;
2896 free(G.traps[sig]);
2897 G.traps[sig] = NULL;
2898 /* There is no signal for 0 (EXIT) */
2899 if (sig == 0)
2900 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002901 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002902 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02002903 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002904 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002905 continue;
2906 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002907 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002908 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002909}
2910
2911#else /* !BB_MMU */
2912
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002913static void re_execute_shell(char ***to_free, const char *s,
2914 char *g_argv0, char **g_argv,
2915 char **builtin_argv) NORETURN;
2916static void re_execute_shell(char ***to_free, const char *s,
2917 char *g_argv0, char **g_argv,
2918 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002919{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002920 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002921 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002922 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002923# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002924 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002925# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002926 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002927 unsigned cnt;
2928
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002929 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002930 argv = heredoc_argv;
2931 argv[0] = (char *) G.argv0_for_re_execing;
2932 argv[1] = (char *) "-<";
2933 argv[2] = (char *) s;
2934 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002935 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002936 goto do_exec;
2937 }
2938
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002939 cnt = 0;
2940 pp = builtin_argv;
2941 if (pp) while (*pp++)
2942 cnt++;
2943
Denys Vlasenkodea47882009-10-09 15:40:49 +02002944 sprintf(param_buf, "-$%x:%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002945 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02002946 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002947 , (unsigned) G.last_bg_pid
2948 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002949 , cnt
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002950 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002951 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002952 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002953 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002954 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002955 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002956 for (cur = G.top_var; cur; cur = cur->next) {
2957 if (!cur->flg_export || cur->flg_read_only)
2958 cnt += 2;
2959 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002960# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002961 for (funcp = G.top_func; funcp; funcp = funcp->next)
2962 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002963# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002964 pp = g_argv;
2965 while (*pp++)
2966 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002967 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002968 *pp++ = (char *) G.argv0_for_re_execing;
2969 *pp++ = param_buf;
2970 for (cur = G.top_var; cur; cur = cur->next) {
2971 if (cur->varstr == hush_version_str)
2972 continue;
2973 if (cur->flg_read_only) {
2974 *pp++ = (char *) "-R";
2975 *pp++ = cur->varstr;
2976 } else if (!cur->flg_export) {
2977 *pp++ = (char *) "-V";
2978 *pp++ = cur->varstr;
2979 }
2980 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002981# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002982 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2983 *pp++ = (char *) "-F";
2984 *pp++ = funcp->name;
2985 *pp++ = funcp->body_as_string;
2986 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002987# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002988 /* We can pass activated traps here. Say, -Tnn:trap_string
2989 *
2990 * However, POSIX says that subshells reset signals with traps
2991 * to SIG_DFL.
2992 * I tested bash-3.2 and it not only does that with true subshells
2993 * of the form ( list ), but with any forked children shells.
2994 * I set trap "echo W" WINCH; and then tried:
2995 *
2996 * { echo 1; sleep 20; echo 2; } &
2997 * while true; do echo 1; sleep 20; echo 2; break; done &
2998 * true | { echo 1; sleep 20; echo 2; } | cat
2999 *
3000 * In all these cases sending SIGWINCH to the child shell
3001 * did not run the trap. If I add trap "echo V" WINCH;
3002 * _inside_ group (just before echo 1), it works.
3003 *
3004 * I conclude it means we don't need to pass active traps here.
3005 * exec syscall below resets them to SIG_DFL for us.
3006 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003007 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003008 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003009 if (builtin_argv) {
3010 while (*++builtin_argv)
3011 *pp++ = *builtin_argv;
3012 *pp++ = (char *) "";
3013 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003014 *pp++ = g_argv0;
3015 while (*g_argv)
3016 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003017 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003018 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003019
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003020 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003021 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
3022 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003023 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003024 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003025 if (argv[0][0] == '/')
3026 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003027 xfunc_error_retval = 127;
3028 bb_error_msg_and_die("can't re-execute the shell");
3029}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003030#endif /* !BB_MMU */
3031
3032
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003033static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003034{
3035 struct fd_pair pair;
3036 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003037 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003038 /* the _body_ of heredoc (misleading field name) */
3039 const char *heredoc = redir->rd_filename;
3040 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003041#if !BB_MMU
3042 char **to_free;
3043#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003044
3045 expanded = NULL;
3046 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
3047 expanded = expand_pseudo_dquoted(heredoc);
3048 if (expanded)
3049 heredoc = expanded;
3050 }
3051 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003052
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00003053 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003054 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003055 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003056
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003057 /* Try writing without forking. Newer kernels have
3058 * dynamically growing pipes. Must use non-blocking write! */
3059 ndelay_on(pair.wr);
3060 while (1) {
3061 written = write(pair.wr, heredoc, len);
3062 if (written <= 0)
3063 break;
3064 len -= written;
3065 if (len == 0) {
3066 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00003067 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003068 return;
3069 }
3070 heredoc += written;
3071 }
3072 ndelay_off(pair.wr);
3073
3074 /* Okay, pipe buffer was not big enough */
3075 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003076 * for the unsuspecting parent process. Child creates a grandchild
3077 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003078 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003079#if !BB_MMU
3080 to_free = NULL;
3081#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003082 pid = vfork();
3083 if (pid < 0)
3084 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003085 if (pid == 0) {
3086 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00003087 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003088 pid = BB_MMU ? fork() : vfork();
3089 if (pid < 0)
3090 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3091 if (pid != 0)
3092 _exit(0);
3093 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003094 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003095#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003096 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003097 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003098#else
3099 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003100 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003101 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003102#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003103 }
3104 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003105#if ENABLE_HUSH_FAST
3106 G.count_SIGCHLD++;
3107//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3108#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003109 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003110#if !BB_MMU
3111 free(to_free);
3112#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003113 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003114 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003115 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003116}
3117
Eric Andersen25f27032001-04-26 23:22:31 +00003118/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3119 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003120static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003121{
3122 int openfd, mode;
3123 struct redir_struct *redir;
3124
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003125 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003126 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003127 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003128 if (squirrel && redir->rd_fd < 3
3129 && squirrel[redir->rd_fd] < 0
3130 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003131 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003132 }
3133 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3134 * of the heredoc */
3135 debug_printf_parse("set heredoc '%s'\n",
3136 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003137 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003138 continue;
3139 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003140
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003141 if (redir->rd_dup == REDIRFD_TO_FILE) {
3142 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003143 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003144 if (redir->rd_filename == NULL) {
3145 /* Something went wrong in the parse.
3146 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003147 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003148 continue;
3149 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003150 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003151 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003152 openfd = open_or_warn(p, mode);
3153 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003154 if (openfd < 0) {
3155 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003156 * bash and ash both lose it as well (though zsh doesn't!) */
3157//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003158 return 1;
3159 }
3160 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003161 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003162 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003163 }
3164
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003165 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003166 if (squirrel && redir->rd_fd < 3
3167 && squirrel[redir->rd_fd] < 0
3168 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003169 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003170 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003171 if (openfd == REDIRFD_CLOSE) {
3172 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003173 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003174 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003175 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003176 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003177 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003178 }
Eric Andersen25f27032001-04-26 23:22:31 +00003179 }
3180 }
3181 return 0;
3182}
3183
3184static void restore_redirects(int squirrel[])
3185{
3186 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003187 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003188 fd = squirrel[i];
3189 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003190 /* We simply die on error */
3191 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003192 }
3193 }
3194}
3195
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003196
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003197static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003198
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003199/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003200static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003201{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003202 char **p;
3203 struct command *command;
3204 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003205 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003206
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003207 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003208 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003209 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003210 for (i = 0; i < pi->num_cmds; i++) {
3211 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003212 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003213 if (command->argv) {
3214 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003215 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003216 }
3217 free_strings(command->argv);
3218 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003219 }
3220 /* not "else if": on syntax error, we may have both! */
3221 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003222 debug_printf_clean(" begin group (cmd_type:%d)\n",
3223 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003224 free_pipe_list(command->group);
3225 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003226 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003227 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003228 /* else is crucial here.
3229 * If group != NULL, child_func is meaningless */
3230#if ENABLE_HUSH_FUNCTIONS
3231 else if (command->child_func) {
3232 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3233 command->child_func->parent_cmd = NULL;
3234 }
3235#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003236#if !BB_MMU
3237 free(command->group_as_string);
3238 command->group_as_string = NULL;
3239#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003240 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003241 debug_printf_clean(" redirect %d%s",
3242 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003243 /* guard against the case >$FOO, where foo is unset or blank */
3244 if (r->rd_filename) {
3245 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3246 free(r->rd_filename);
3247 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003248 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003249 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003250 rnext = r->next;
3251 free(r);
3252 }
3253 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003254 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003255 free(pi->cmds); /* children are an array, they get freed all at once */
3256 pi->cmds = NULL;
3257#if ENABLE_HUSH_JOB
3258 free(pi->cmdtext);
3259 pi->cmdtext = NULL;
3260#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003261}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003262
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003263static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003264{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003265 struct pipe *pi, *next;
3266
3267 for (pi = head; pi; pi = next) {
3268#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003269 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003270#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003271 free_pipe(pi);
3272 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003273 next = pi->next;
3274 /*pi->next = NULL;*/
3275 free(pi);
3276 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003277}
3278
3279
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003280static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003281#if BB_MMU
3282#define parse_stream(pstring, input, end_trigger) \
3283 parse_stream(input, end_trigger)
3284#endif
3285static struct pipe *parse_stream(char **pstring,
3286 struct in_str *input,
3287 int end_trigger);
3288static void parse_and_run_string(const char *s);
3289
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003290
Mike Frysinger93cadc22009-05-27 17:06:25 -04003291static char *find_in_path(const char *arg)
3292{
3293 char *ret = NULL;
3294 const char *PATH = get_local_var_value("PATH");
3295
3296 if (!PATH)
3297 return NULL;
3298
3299 while (1) {
3300 const char *end = strchrnul(PATH, ':');
3301 int sz = end - PATH; /* must be int! */
3302
3303 free(ret);
3304 if (sz != 0) {
3305 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3306 } else {
3307 /* We have xxx::yyyy in $PATH,
3308 * it means "use current dir" */
3309 ret = xstrdup(arg);
3310 }
3311 if (access(ret, F_OK) == 0)
3312 break;
3313
3314 if (*end == '\0') {
3315 free(ret);
3316 return NULL;
3317 }
3318 PATH = end + 1;
3319 }
3320
3321 return ret;
3322}
3323
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003324static const struct built_in_command* find_builtin_helper(const char *name,
3325 const struct built_in_command *x,
3326 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003327{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003328 while (x != end) {
3329 if (strcmp(name, x->cmd) != 0) {
3330 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003331 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003332 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003333 debug_printf_exec("found builtin '%s'\n", name);
3334 return x;
3335 }
3336 return NULL;
3337}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003338static const struct built_in_command* find_builtin1(const char *name)
3339{
3340 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3341}
3342static const struct built_in_command* find_builtin(const char *name)
3343{
3344 const struct built_in_command *x = find_builtin1(name);
3345 if (x)
3346 return x;
3347 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3348}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003349
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003350#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003351static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003352{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003353 struct function **funcpp = &G.top_func;
3354 while (*funcpp) {
3355 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003356 break;
3357 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003358 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003359 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003360 return funcpp;
3361}
3362
3363static const struct function *find_function(const char *name)
3364{
3365 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003366 if (funcp)
3367 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003368 return funcp;
3369}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003370
Denis Vlasenkobc569742009-04-12 20:35:19 +00003371/* Note: takes ownership on name ptr */
3372static struct function *new_function(char *name)
3373{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003374 struct function **funcpp = find_function_slot(name);
3375 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003376
Denys Vlasenko873273d2009-09-12 14:47:41 +02003377 if (funcp != NULL) {
3378 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003379 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3380 if (!cmd) {
3381 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3382 free(funcp->name);
3383 /* Note: if !funcp->body, do not free body_as_string!
3384 * This is a special case of "-F name body" function:
3385 * body_as_string was not malloced! */
3386 if (funcp->body) {
3387 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003388# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003389 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003390# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003391 }
3392 } else {
3393 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3394 cmd->argv[0] = funcp->name;
3395 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003396# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003397 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003398# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003399 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003400 } else {
3401 debug_printf_exec("remembering new function '%s'\n", name);
3402 funcp = *funcpp = xzalloc(sizeof(*funcp));
3403 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003404 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003405
Denis Vlasenkobc569742009-04-12 20:35:19 +00003406 funcp->name = name;
3407 return funcp;
3408}
3409
Denis Vlasenko40e84372009-04-18 11:23:38 +00003410static void unset_func(const char *name)
3411{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003412 struct function **funcpp = find_function_slot(name);
3413 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003414
Denys Vlasenko873273d2009-09-12 14:47:41 +02003415 if (funcp != NULL) {
3416 debug_printf_exec("freeing function '%s'\n", funcp->name);
3417 *funcpp = funcp->next;
3418 /* funcp is unlinked now, deleting it.
3419 * Note: if !funcp->body, the function was created by
3420 * "-F name body", do not free ->body_as_string
3421 * and ->name as they were not malloced. */
3422 if (funcp->body) {
3423 free_pipe_list(funcp->body);
3424 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003425# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003426 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003427# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003428 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003429 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003430 }
3431}
3432
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003433# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003434#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003435 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003436# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003437static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003438 const struct function *funcp,
3439 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003440static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003441 const struct function *funcp,
3442 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003443{
3444# if BB_MMU
3445 int n = 1;
3446
3447 argv[0] = G.global_argv[0];
3448 G.global_argv = argv;
3449 while (*++argv)
3450 n++;
3451 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003452 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003453 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003454 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003455 _exit(n);
3456# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003457 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003458 funcp->body_as_string,
3459 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003460 argv + 1,
3461 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003462# endif
3463}
3464
3465static int run_function(const struct function *funcp, char **argv)
3466{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003467 int rc;
3468 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003469 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003470
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003471 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003472
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003473 /* "we are in function, ok to use return" */
3474 sv_flg = G.flag_return_in_progress;
3475 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003476# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003477 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003478# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003479
Denis Vlasenkobc569742009-04-12 20:35:19 +00003480 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003481# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003482 if (!funcp->body) {
3483 /* Function defined by -F */
3484 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003485 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003486 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003487# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003488 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003489 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003490 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003491
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003492# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003493 {
3494 struct variable *var;
3495 struct variable **var_pp;
3496
3497 var_pp = &G.top_var;
3498 while ((var = *var_pp) != NULL) {
3499 if (var->func_nest_level < G.func_nest_level) {
3500 var_pp = &var->next;
3501 continue;
3502 }
3503 /* Unexport */
3504 if (var->flg_export)
3505 bb_unsetenv(var->varstr);
3506 /* Remove from global list */
3507 *var_pp = var->next;
3508 /* Free */
3509 if (!var->max_len)
3510 free(var->varstr);
3511 free(var);
3512 }
3513 G.func_nest_level--;
3514 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003515# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003516 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003517
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003518 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003519
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003520 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003521}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003522#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003523
3524
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003525#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003526#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003527 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003528#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003529#define exec_builtin(to_free, x, argv) \
3530 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003531#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003532static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003533 const struct built_in_command *x,
3534 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003535static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003536 const struct built_in_command *x,
3537 char **argv)
3538{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003539#if BB_MMU
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003540 int rcode = x->function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003541 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003542 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003543#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003544 /* On NOMMU, we must never block!
3545 * Example: { sleep 99 | read line; } & echo Ok
3546 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003547 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003548 argv[0],
3549 G.global_argv[0],
3550 G.global_argv + 1,
3551 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003552#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003553}
3554
3555
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003556static void execvp_or_die(char **argv) NORETURN;
3557static void execvp_or_die(char **argv)
3558{
3559 debug_printf_exec("execing '%s'\n", argv[0]);
3560 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3561 execvp(argv[0], argv);
3562 bb_perror_msg("can't execute '%s'", argv[0]);
3563 _exit(127); /* bash compat */
3564}
3565
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003566#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003567#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3568 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3569#define pseudo_exec(nommu_save, command, argv_expanded) \
3570 pseudo_exec(command, argv_expanded)
3571#endif
3572
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003573/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003574 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003575 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003576 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003577 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003578static void pseudo_exec_argv(nommu_save_t *nommu_save,
3579 char **argv, int assignment_cnt,
3580 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003581static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003582 char **argv, int assignment_cnt,
3583 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003584{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003585 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003586
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003587 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003588 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003589 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003590
Denis Vlasenko9504e442008-10-29 01:19:15 +00003591 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003592#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003593 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003594 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003595 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003596 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003597#else
3598 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003599 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003600#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003601 if (argv_expanded) {
3602 argv = argv_expanded;
3603 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003604 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003605#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003606 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003607#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003608 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003609
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003610#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3611 if (strchr(argv[0], '/') != NULL)
3612 goto skip;
3613#endif
3614
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003615 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003616 * Depending on context, this might be redundant. But it's
3617 * easier to waste a few CPU cycles than it is to figure out
3618 * if this is one of those cases.
3619 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003620 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003621 /* On NOMMU, it is more expensive to re-execute shell
3622 * just in order to run echo or test builtin.
3623 * It's better to skip it here and run corresponding
3624 * non-builtin later. */
3625 const struct built_in_command *x;
3626 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003627 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003628 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003629 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003630 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003631#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003632 /* Check if the command matches any functions */
3633 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003634 const struct function *funcp = find_function(argv[0]);
3635 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003636 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003637 }
3638 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003639#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003640
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003641#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003642 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003643 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003644 int a = find_applet_by_name(argv[0]);
3645 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003646# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003647 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003648 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003649 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003650 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003651# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003652 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003653 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003654 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3655 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003656 /* If they called chroot or otherwise made the binary no longer
3657 * executable, fall through */
3658 }
3659 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003660#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003661
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003662#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003663 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003664#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003665 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003666}
3667
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003668/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003669 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003670static void pseudo_exec(nommu_save_t *nommu_save,
3671 struct command *command,
3672 char **argv_expanded) NORETURN;
3673static void pseudo_exec(nommu_save_t *nommu_save,
3674 struct command *command,
3675 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003676{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003677 if (command->argv) {
3678 pseudo_exec_argv(nommu_save, command->argv,
3679 command->assignment_cnt, argv_expanded);
3680 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003681
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003682 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003683 /* Cases when we are here:
3684 * ( list )
3685 * { list } &
3686 * ... | ( list ) | ...
3687 * ... | { list } | ...
3688 */
3689#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003690 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003691 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003692 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003693 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003694 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003695 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003696 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003697#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003698 re_execute_shell(&nommu_save->argv_from_re_execing,
3699 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003700 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003701 G.global_argv + 1,
3702 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003703#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003704 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003705
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003706 /* Case when we are here: ... | >file */
3707 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003708 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003709}
3710
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003711#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003712static const char *get_cmdtext(struct pipe *pi)
3713{
3714 char **argv;
3715 char *p;
3716 int len;
3717
3718 /* This is subtle. ->cmdtext is created only on first backgrounding.
3719 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003720 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003721 if (pi->cmdtext)
3722 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003723 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003724 if (!argv || !argv[0]) {
3725 pi->cmdtext = xzalloc(1);
3726 return pi->cmdtext;
3727 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003728
3729 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003730 do {
3731 len += strlen(*argv) + 1;
3732 } while (*++argv);
3733 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003734 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003735 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003736 do {
3737 len = strlen(*argv);
3738 memcpy(p, *argv, len);
3739 p += len;
3740 *p++ = ' ';
3741 } while (*++argv);
3742 p[-1] = '\0';
3743 return pi->cmdtext;
3744}
3745
Eric Andersenbafd94f2001-05-02 16:11:59 +00003746static void insert_bg_job(struct pipe *pi)
3747{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003748 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003749 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003750
3751 /* Linear search for the ID of the job to use */
3752 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003753 for (job = G.job_list; job; job = job->next)
3754 if (job->jobid >= pi->jobid)
3755 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003756
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003757 /* Add job to the list of running jobs */
3758 jobp = &G.job_list;
3759 while ((job = *jobp) != NULL)
3760 jobp = &job->next;
3761 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003762
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003763 *job = *pi; /* physical copy */
3764 job->next = NULL;
3765 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3766 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003767 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003768 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003769 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003770 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003771 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003772
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003773 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003774 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3775 /* Last command's pid goes to $! */
3776 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3777 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003778}
3779
Eric Andersenbafd94f2001-05-02 16:11:59 +00003780static void remove_bg_job(struct pipe *pi)
3781{
3782 struct pipe *prev_pipe;
3783
Denis Vlasenko87a86552008-07-29 19:43:10 +00003784 if (pi == G.job_list) {
3785 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003786 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003787 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003788 while (prev_pipe->next != pi)
3789 prev_pipe = prev_pipe->next;
3790 prev_pipe->next = pi->next;
3791 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003792 if (G.job_list)
3793 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003794 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003795 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003796}
Eric Andersen028b65b2001-06-28 01:10:11 +00003797
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003798/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003799static void delete_finished_bg_job(struct pipe *pi)
3800{
3801 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003802 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003803 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003804 free(pi);
3805}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003806#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003807
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003808/* Check to see if any processes have exited -- if they
3809 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003810static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003811{
Eric Andersenc798b072001-06-22 06:23:03 +00003812 int attributes;
3813 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003814#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003815 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003816#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003817 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003818 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003819
Denis Vlasenkod5762932009-03-31 11:22:57 +00003820 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3821
Eric Andersenc798b072001-06-22 06:23:03 +00003822 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003823 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003824 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003825
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003826 errno = 0;
3827#if ENABLE_HUSH_FAST
3828 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3829//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3830//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003831 /* There was neither fork nor SIGCHLD since last waitpid */
3832 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003833 if (!G.we_have_children) {
3834 errno = ECHILD;
3835 return -1;
3836 }
3837 if (fg_pipe == NULL) { /* is WNOHANG set? */
3838 /* We have children, but they did not exit
3839 * or stop yet (we saw no SIGCHLD) */
3840 return 0;
3841 }
3842 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3843 }
3844#endif
3845
Denis Vlasenko1359da62007-04-21 23:27:30 +00003846/* Do we do this right?
3847 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003848 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003849 * [3]+ Stopped sleep 20 | false
3850 * bash-3.00# echo $?
3851 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003852 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003853 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003854 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003855 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003856 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003857 int dead;
3858
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003859#if ENABLE_HUSH_FAST
3860 i = G.count_SIGCHLD;
3861#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003862 childpid = waitpid(-1, &status, attributes);
3863 if (childpid <= 0) {
3864 if (childpid && errno != ECHILD)
3865 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003866#if ENABLE_HUSH_FAST
3867 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003868 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003869 G.handled_SIGCHLD = i;
3870//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3871 }
3872#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003873 break;
3874 }
3875 dead = WIFEXITED(status) || WIFSIGNALED(status);
3876
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003877#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003878 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003879 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003880 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3881 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003882 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003883 childpid, WTERMSIG(status), WEXITSTATUS(status));
3884 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003885 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003886 childpid, WEXITSTATUS(status));
3887#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003888 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003889 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003890 for (i = 0; i < fg_pipe->num_cmds; i++) {
3891 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3892 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003893 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003894 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003895 fg_pipe->cmds[i].pid = 0;
3896 fg_pipe->alive_cmds--;
3897 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003898 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003899 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003900 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003901 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003902 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00003903 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003904 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003905 */
3906 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003907 int sig = WTERMSIG(status);
3908 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003909 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003910 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003911 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003912 fg_pipe->cmds[i].is_stopped = 1;
3913 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003914 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003915 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3916 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3917 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003918 /* All processes in fg pipe have exited or stopped */
3919/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3920 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3921 * and "killall -STOP cat" */
3922 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003923#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003924 if (fg_pipe->alive_cmds)
3925 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003926#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003927 return rcode;
3928 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02003929 if (!fg_pipe->alive_cmds)
3930 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003931 }
3932 /* There are still running processes in the fg pipe */
3933 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003934 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003935 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003936 }
3937
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003938#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003939 /* We asked to wait for bg or orphaned children */
3940 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003941 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003942 for (i = 0; i < pi->num_cmds; i++) {
3943 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003944 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003945 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003946 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003947 /* Happens when shell is used as init process (init=/bin/sh) */
3948 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003949 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003950
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003951 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003952 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003953 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003954 pi->cmds[i].pid = 0;
3955 pi->alive_cmds--;
3956 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003957 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003958 printf(JOB_STATUS_FORMAT, pi->jobid,
3959 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003960 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003961 }
3962 } else {
3963 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003964 pi->cmds[i].is_stopped = 1;
3965 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003966 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003967#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003968 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003969
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003970 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003971}
3972
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003973#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003974static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3975{
3976 pid_t p;
3977 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003978 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003979 /* Job finished, move the shell to the foreground */
3980 p = getpgrp(); /* our process group id */
3981 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3982 tcsetpgrp(G_interactive_fd, p);
3983 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003984 return rcode;
3985}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003986#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003987
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003988/* Start all the jobs, but don't wait for anything to finish.
3989 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003990 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003991 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003992 * to finish to determine the exit status of the pipe. If the pipe
3993 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003994 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003995 * return value.
3996 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003997 * Returns -1 only if started some children. IOW: we have to
3998 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003999 *
4000 * The only case when we do not need to [v]fork is when the pipe
4001 * is single, non-backgrounded, non-subshell command. Examples:
4002 * cmd ; ... { list } ; ...
4003 * cmd && ... { list } && ...
4004 * cmd || ... { list } || ...
4005 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
4006 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00004007 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00004008 *
4009 * Cases when we must fork:
4010 * non-single: cmd | cmd
4011 * backgrounded: cmd & { list } &
4012 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00004013 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02004014static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004015{
Denis Vlasenko552433b2009-04-04 19:29:21 +00004016 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004017 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004018 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004019 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004020 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004021 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004022 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004023 /* it is not always needed, but we aim to smaller code */
4024 int squirrel[] = { -1, -1, -1 };
4025 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004026
Denis Vlasenko552433b2009-04-04 19:29:21 +00004027 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004028 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004029
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004030 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004031 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004032 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004033 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004034
Denis Vlasenko552433b2009-04-04 19:29:21 +00004035 if (pi->num_cmds != 1
4036 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004037 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00004038 ) {
4039 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004040 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004041
Denis Vlasenko552433b2009-04-04 19:29:21 +00004042 pi->alive_cmds = 1;
4043
4044 debug_printf_exec(": group:%p argv:'%s'\n",
4045 command->group, command->argv ? command->argv[0] : "NONE");
4046
4047 if (command->group) {
4048#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004049 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004050 /* "executing" func () { list } */
4051 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004052
Denis Vlasenkobc569742009-04-12 20:35:19 +00004053 funcp = new_function(command->argv[0]);
4054 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004055 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004056# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004057 funcp->body_as_string = command->group_as_string;
4058 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004059# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004060 command->group = NULL;
4061 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00004062 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
4063 funcp->parent_cmd = command;
4064 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004065
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004066 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
4067 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00004068 return EXIT_SUCCESS;
4069 }
4070#endif
4071 /* { list } */
4072 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004073 rcode = 1; /* exitcode if redir failed */
4074 if (setup_redirects(command, squirrel) == 0) {
4075 debug_printf_exec(": run_list\n");
4076 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004077 }
Eric Andersen04407e52001-06-07 16:42:05 +00004078 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004079 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004080 debug_leave();
4081 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004082 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004083 }
4084
Denis Vlasenko552433b2009-04-04 19:29:21 +00004085 argv = command->argv ? command->argv : (char **) &null_ptr;
4086 {
4087 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004088#if ENABLE_HUSH_FUNCTIONS
4089 const struct function *funcp;
4090#else
4091 enum { funcp = 0 };
4092#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004093 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004094 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004095
Denis Vlasenko552433b2009-04-04 19:29:21 +00004096 if (argv[command->assignment_cnt] == NULL) {
4097 /* Assignments, but no command */
4098 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004099 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004100 restore_redirects(squirrel);
4101 /* Set shell variables */
4102 while (*argv) {
4103 p = expand_string_to_string(*argv);
4104 debug_printf_exec("set shell var:'%s'->'%s'\n",
4105 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004106 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004107 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004108 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004109 /* Do we need to flag set_local_var() errors?
4110 * "assignment to readonly var" and "putenv error"
4111 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004112 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004113 debug_leave();
4114 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004115 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004116 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004117
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004118 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004119 if (0) {}
4120#if ENABLE_HUSH_BASH_COMPAT
4121 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004122 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4123 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004124#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004125#ifdef CMD_SINGLEWORD_NOGLOB_COND
4126 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4127 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4128
4129 }
4130#endif
4131 else {
4132 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4133 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004134
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004135 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004136 if (!argv_expanded[0]) {
4137 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004138 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004139 }
4140
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004141 x = find_builtin(argv_expanded[0]);
4142#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004143 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004144 if (!x)
4145 funcp = find_function(argv_expanded[0]);
4146#endif
4147 if (x || funcp) {
4148 if (!funcp) {
4149 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
4150 debug_printf("exec with redirects only\n");
4151 rcode = setup_redirects(command, NULL);
4152 goto clean_up_and_ret1;
4153 }
Eric Andersen25f27032001-04-26 23:22:31 +00004154 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004155 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004156 * This is perfect for work that comes after exec().
4157 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004158 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004159 rcode = setup_redirects(command, squirrel);
4160 if (rcode == 0) {
4161 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004162 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004163 if (!funcp) {
4164 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004165 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004166 rcode = x->function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004167 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004168 }
4169#if ENABLE_HUSH_FUNCTIONS
4170 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004171# if ENABLE_HUSH_LOCAL
4172 struct variable **sv;
4173 sv = G.shadowed_vars_pp;
4174 G.shadowed_vars_pp = &old_vars;
4175# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004176 debug_printf_exec(": function '%s' '%s'...\n",
4177 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004178 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004179# if ENABLE_HUSH_LOCAL
4180 G.shadowed_vars_pp = sv;
4181# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004182 }
4183#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004184 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004185#if ENABLE_FEATURE_SH_STANDALONE
4186 clean_up_and_ret:
4187#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004188 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004189 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004190 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004191 clean_up_and_ret1:
4192 free(argv_expanded);
4193 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004194 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004195 debug_printf_exec("run_pipe return %d\n", rcode);
4196 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004197 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004198
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004199#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004200 i = find_applet_by_name(argv_expanded[0]);
4201 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004202 rcode = setup_redirects(command, squirrel);
4203 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004204 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004205 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004206 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004207 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004208 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004209 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004210 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004211 }
4212#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00004213 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004214 }
4215
Denis Vlasenko552433b2009-04-04 19:29:21 +00004216 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004217 /* NB: argv_expanded may already be created, and that
4218 * might include `cmd` runs! Do not rerun it! We *must*
4219 * use argv_expanded if it's non-NULL */
4220
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004221 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004222 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004223 nextin = 0;
4224
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004225 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004226 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004227#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004228 volatile nommu_save_t nommu_save;
4229 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004230 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004231 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004232 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004233#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004234 command = &(pi->cmds[i]);
4235 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004236 debug_printf_exec(": pipe member '%s' '%s'...\n",
4237 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004238 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004239 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004240 }
Eric Andersen25f27032001-04-26 23:22:31 +00004241
4242 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004243 pipefds.rd = 0;
4244 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004245 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004246 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004247
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004248 command->pid = BB_MMU ? fork() : vfork();
4249 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004250#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004251 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004252 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004253
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004254 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004255 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004256 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004257 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004258 pgrp = pi->pgrp;
4259 if (pgrp < 0) /* true for 1st process only */
4260 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004261 if (setpgid(0, pgrp) == 0
4262 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004263 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004264 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004265 /* We do it in *every* child, not just first,
4266 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004267 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004268 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004269 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004270#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004271 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4272 /* 1st cmd in backgrounded pipe
4273 * should have its stdin /dev/null'ed */
4274 close(0);
4275 if (open(bb_dev_null, O_RDONLY))
4276 xopen("/", O_RDONLY);
4277 } else {
4278 xmove_fd(nextin, 0);
4279 }
4280 xmove_fd(pipefds.wr, 1);
4281 if (pipefds.rd > 1)
4282 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004283 /* Like bash, explicit redirects override pipes,
4284 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004285 if (setup_redirects(command, NULL))
4286 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004287
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004288 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004289 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4290
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004291 /* Stores to nommu_save list of env vars putenv'ed
4292 * (NOMMU, on MMU we don't need that) */
4293 /* cast away volatility... */
4294 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004295 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004296 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004297
Denis Vlasenkof9375282009-04-05 19:13:39 +00004298 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004299#if ENABLE_HUSH_FAST
4300 G.count_SIGCHLD++;
4301//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4302#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004303 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004304#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004305 /* Clean up after vforked child */
4306 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004307 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004308 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004309 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004310#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004311 free(argv_expanded);
4312 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004313 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004314 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004315 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004316 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004317 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004318#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004319 /* Second and next children need to know pid of first one */
4320 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004321 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004322#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004323 }
Eric Andersen25f27032001-04-26 23:22:31 +00004324
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004325 if (i)
4326 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004327 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004328 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004329 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004330 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004331 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004332
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004333 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004334 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004335 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4336 return 1;
4337 }
4338
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004339 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004340 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004341 return -1;
4342}
4343
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004344#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004345static void debug_print_tree(struct pipe *pi, int lvl)
4346{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004347 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004348 [PIPE_SEQ] = "SEQ",
4349 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004350 [PIPE_OR ] = "OR" ,
4351 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004352 };
4353 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004354 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004355# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004356 [RES_IF ] = "IF" ,
4357 [RES_THEN ] = "THEN" ,
4358 [RES_ELIF ] = "ELIF" ,
4359 [RES_ELSE ] = "ELSE" ,
4360 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004361# endif
4362# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004363 [RES_FOR ] = "FOR" ,
4364 [RES_WHILE] = "WHILE",
4365 [RES_UNTIL] = "UNTIL",
4366 [RES_DO ] = "DO" ,
4367 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004368# endif
4369# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004370 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004371# endif
4372# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004373 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004374 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004375 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004376 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004377 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004378# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004379 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004380 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004381 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004382 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004383 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004384 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004385 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004386# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004387 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004388# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004389 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004390
4391 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004392
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004393 pin = 0;
4394 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004395 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4396 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004397 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004398 while (prn < pi->num_cmds) {
4399 struct command *command = &pi->cmds[prn];
4400 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004401
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004402 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004403 lvl*2, "", prn,
4404 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004405 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004406 fprintf(stderr, " group %s: (argv=%p)\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004407 CMDTYPE[command->cmd_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004408 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004409 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004410 prn++;
4411 continue;
4412 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004413 if (argv) while (*argv) {
4414 fprintf(stderr, " '%s'", *argv);
4415 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004416 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004417 fprintf(stderr, "\n");
4418 prn++;
4419 }
4420 pi = pi->next;
4421 pin++;
4422 }
4423}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004424#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004425
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004426/* NB: called by pseudo_exec, and therefore must not modify any
4427 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004428static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004429{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004430#if ENABLE_HUSH_CASE
4431 char *case_word = NULL;
4432#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004433#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004434 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004435 char **for_lcur = NULL;
4436 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004437#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004438 smallint last_followup;
4439 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004440#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004441 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004442#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004443 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004444#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004445#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004446 smallint rword; /* enum reserved_style */
4447 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004448#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004449
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004450 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004451 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004452
Denis Vlasenko06810332007-05-21 23:30:54 +00004453#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004454 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004455 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4456 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004457 continue;
4458 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004459 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004460 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004461 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004462 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004463 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004464 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004465 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004466 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004467 continue;
4468 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004469 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4470 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004471 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004472 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004473 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004474 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004475 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004476 }
4477 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004478#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004479
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004480 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004481 * in order to return, no direct "return" statements please.
4482 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004483
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004484#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004485 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004486#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004487
Denis Vlasenko0e151382009-04-06 18:40:31 +00004488#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004489 rword = RES_NONE;
4490 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004491#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004492 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004493 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004494
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004495 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004496 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004497 if (G.flag_SIGINT)
4498 break;
4499
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004500 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004501 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4502 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004503#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004504 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004505 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004506 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004507 /* start of a loop: remember where loop starts */
4508 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004509 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004510 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004511#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004512 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004513 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004514 if ((rcode == 0 && last_followup == PIPE_OR)
4515 || (rcode != 0 && last_followup == PIPE_AND)
4516 ) {
4517 /* It is "<true> || CMD" or "<false> && CMD"
4518 * and we should not execute CMD */
4519 debug_printf_exec("skipped cmd because of || or &&\n");
4520 last_followup = pi->followup;
4521 continue;
4522 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004523 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004524 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004525 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004526#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004527 if (cond_code) {
4528 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004529 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004530 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004531 /* "if <false> THEN cmd": skip cmd */
4532 continue;
4533 }
4534 } else {
4535 if (rword == RES_ELSE || rword == RES_ELIF) {
4536 /* "if <true> then ... ELSE/ELIF cmd":
4537 * skip cmd and all following ones */
4538 break;
4539 }
4540 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004541#endif
4542#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004543 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004544 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004545 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004546
4547 static const char encoded_dollar_at[] ALIGN1 = {
4548 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4549 }; /* encoded representation of "$@" */
4550 static const char *const encoded_dollar_at_argv[] = {
4551 encoded_dollar_at, NULL
4552 }; /* argv list with one element: "$@" */
4553 char **vals;
4554
4555 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004556 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004557 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004558 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004559 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004560 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004561 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004562 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004563 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004564 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004565 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004566 debug_print_strings("for_list made from", vals);
4567 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004568 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004569 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004570 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004571 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004572 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004573 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004574 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004575 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004576 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004577 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004578 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004579 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004580 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 +02004581 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004582 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004583 if (rword == RES_IN) {
4584 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4585 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004586 if (rword == RES_DONE) {
4587 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004588 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004589#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004590#if ENABLE_HUSH_CASE
4591 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004592 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004593 continue;
4594 }
4595 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004596 char **argv;
4597
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004598 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4599 break;
4600 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004601 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004602 while (*argv) {
4603 char *pattern = expand_string_to_string(*argv);
4604 /* TODO: which FNM_xxx flags to use? */
4605 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4606 free(pattern);
4607 if (cond_code == 0) { /* match! we will execute this branch */
4608 free(case_word); /* make future "word)" stop */
4609 case_word = NULL;
4610 break;
4611 }
4612 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004613 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004614 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004615 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004616 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004617 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004618 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004619 }
4620#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004621 /* Just pressing <enter> in shell should check for jobs.
4622 * OTOH, in non-interactive shell this is useless
4623 * and only leads to extra job checks */
4624 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004625 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004626 goto check_jobs_and_continue;
4627 continue;
4628 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004629
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004630 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004631 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004632 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004633 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004634 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004635 {
4636 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004637#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004638 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004639#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004640 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4641 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004642 /* We ran a builtin, function, or group.
4643 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004644 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004645 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004646 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004647 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004648#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004649 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004650 if (G.flag_break_continue) {
4651 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004652 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004653 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004654 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004655 G.depth_break_continue--;
4656 if (G.depth_break_continue == 0)
4657 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004658 /* else: e.g. "continue 2" should *break* once, *then* continue */
4659 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004660 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004661 goto check_jobs_and_break;
4662 /* "continue": simulate end of loop */
4663 rword = RES_DONE;
4664 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004665 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004666#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004667#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004668 if (G.flag_return_in_progress == 1) {
4669 /* same as "goto check_jobs_and_break" */
4670 checkjobs(NULL);
4671 break;
4672 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004673#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004674 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004675 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004676 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004677 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4678 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004679 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004680#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004681 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004682 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004683#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004684 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004685 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004686 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004687#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004688 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004689 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004690 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004691 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004692 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004693 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004694#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004695 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004696 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004697 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004698 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004699 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004700 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004701 }
4702 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004703
4704 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004705#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004706 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004707 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004708#endif
4709#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004710 /* Beware of "while false; true; do ..."! */
4711 if (pi->next && pi->next->res_word == RES_DO) {
4712 if (rword == RES_WHILE) {
4713 if (rcode) {
4714 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004715 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004716 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4717 goto check_jobs_and_break;
4718 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004719 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004720 if (rword == RES_UNTIL) {
4721 if (!rcode) {
4722 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004723 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004724 checkjobs(NULL);
4725 break;
4726 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004727 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004728 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004729#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004730
4731 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004732 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004733 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004734
4735#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004736 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004737#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004738#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004739 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004740 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004741 free(for_list);
4742#endif
4743#if ENABLE_HUSH_CASE
4744 free(case_word);
4745#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004746 debug_leave();
4747 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004748 return rcode;
4749}
4750
Eric Andersen25f27032001-04-26 23:22:31 +00004751/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004752static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004753{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004754 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004755 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004756 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004757 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004758 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004759 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004760 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004761 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004762 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004763 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004764 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004765 return rcode;
4766}
4767
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004768
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004769static struct pipe *new_pipe(void)
4770{
Eric Andersen25f27032001-04-26 23:22:31 +00004771 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004772 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004773 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004774 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004775 return pi;
4776}
4777
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004778/* Command (member of a pipe) is complete, or we start a new pipe
4779 * if ctx->command is NULL.
4780 * No errors possible here.
4781 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004782static int done_command(struct parse_context *ctx)
4783{
4784 /* The command is really already in the pipe structure, so
4785 * advance the pipe counter and make a new, null command. */
4786 struct pipe *pi = ctx->pipe;
4787 struct command *command = ctx->command;
4788
4789 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004790 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004791 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004792 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004793 }
4794 pi->num_cmds++;
4795 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004796 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004797 } else {
4798 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4799 }
4800
4801 /* Only real trickiness here is that the uncommitted
4802 * command structure is not counted in pi->num_cmds. */
4803 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004804 ctx->command = command = &pi->cmds[pi->num_cmds];
4805 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004806 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004807 return pi->num_cmds; /* used only for 0/nonzero check */
4808}
4809
4810static void done_pipe(struct parse_context *ctx, pipe_style type)
4811{
4812 int not_null;
4813
4814 debug_printf_parse("done_pipe entered, followup %d\n", type);
4815 /* Close previous command */
4816 not_null = done_command(ctx);
4817 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004818#if HAS_KEYWORDS
4819 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4820 ctx->ctx_inverted = 0;
4821 ctx->pipe->res_word = ctx->ctx_res_w;
4822#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004823
4824 /* Without this check, even just <enter> on command line generates
4825 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004826 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004827 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004828#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004829 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004830#endif
4831#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004832 || ctx->ctx_res_w == RES_DONE
4833 || ctx->ctx_res_w == RES_FOR
4834 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004835#endif
4836#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004837 || ctx->ctx_res_w == RES_ESAC
4838#endif
4839 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004840 struct pipe *new_p;
4841 debug_printf_parse("done_pipe: adding new pipe: "
4842 "not_null:%d ctx->ctx_res_w:%d\n",
4843 not_null, ctx->ctx_res_w);
4844 new_p = new_pipe();
4845 ctx->pipe->next = new_p;
4846 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004847 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004848 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004849 * This is used to control execution.
4850 * RES_FOR and RES_IN are NOT sticky (needed to support
4851 * cases where variable or value happens to match a keyword):
4852 */
4853#if ENABLE_HUSH_LOOPS
4854 if (ctx->ctx_res_w == RES_FOR
4855 || ctx->ctx_res_w == RES_IN)
4856 ctx->ctx_res_w = RES_NONE;
4857#endif
4858#if ENABLE_HUSH_CASE
4859 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004860 ctx->ctx_res_w = RES_CASE_BODY;
4861 if (ctx->ctx_res_w == RES_CASE)
4862 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004863#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004864 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004865 /* Create the memory for command, roughly:
4866 * ctx->pipe->cmds = new struct command;
4867 * ctx->command = &ctx->pipe->cmds[0];
4868 */
4869 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004870 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004871 }
4872 debug_printf_parse("done_pipe return\n");
4873}
4874
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004875static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004876{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004877 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004878 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004879 /* Create the memory for command, roughly:
4880 * ctx->pipe->cmds = new struct command;
4881 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004882 */
4883 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004884}
4885
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004886/* If a reserved word is found and processed, parse context is modified
4887 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004888 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004889#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004890struct reserved_combo {
4891 char literal[6];
4892 unsigned char res;
4893 unsigned char assignment_flag;
4894 int flag;
4895};
4896enum {
4897 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004898# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004899 FLAG_IF = (1 << RES_IF ),
4900 FLAG_THEN = (1 << RES_THEN ),
4901 FLAG_ELIF = (1 << RES_ELIF ),
4902 FLAG_ELSE = (1 << RES_ELSE ),
4903 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004904# endif
4905# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004906 FLAG_FOR = (1 << RES_FOR ),
4907 FLAG_WHILE = (1 << RES_WHILE),
4908 FLAG_UNTIL = (1 << RES_UNTIL),
4909 FLAG_DO = (1 << RES_DO ),
4910 FLAG_DONE = (1 << RES_DONE ),
4911 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004912# endif
4913# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004914 FLAG_MATCH = (1 << RES_MATCH),
4915 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004916# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004917 FLAG_START = (1 << RES_XXXX ),
4918};
4919
4920static const struct reserved_combo* match_reserved_word(o_string *word)
4921{
Eric Andersen25f27032001-04-26 23:22:31 +00004922 /* Mostly a list of accepted follow-up reserved words.
4923 * FLAG_END means we are done with the sequence, and are ready
4924 * to turn the compound list into a command.
4925 * FLAG_START means the word must start a new compound list.
4926 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004927 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004928# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004929 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4930 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4931 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4932 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4933 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4934 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004935# endif
4936# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004937 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4938 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4939 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4940 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4941 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4942 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004943# endif
4944# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004945 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4946 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004947# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004948 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004949 const struct reserved_combo *r;
4950
4951 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4952 if (strcmp(word->data, r->literal) == 0)
4953 return r;
4954 }
4955 return NULL;
4956}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004957/* Return 0: not a keyword, 1: keyword
4958 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004959static int reserved_word(o_string *word, struct parse_context *ctx)
4960{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004961# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004962 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004963 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004964 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004965# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004966 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004967
Denis Vlasenkobb929512009-04-16 10:59:40 +00004968 if (word->o_quoted)
4969 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004970 r = match_reserved_word(word);
4971 if (!r)
4972 return 0;
4973
4974 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004975# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004976 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4977 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004978 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004979 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004980# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004981 if (r->flag == 0) { /* '!' */
4982 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004983 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004984 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004985 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004986 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004987 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004988 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004989 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004990 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004991
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004992 old = xmalloc(sizeof(*old));
4993 debug_printf_parse("push stack %p\n", old);
4994 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004995 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004996 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004997 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004998 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004999 ctx->ctx_res_w = RES_SNTX;
5000 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005001 } else {
5002 /* "{...} fi" is ok. "{...} if" is not
5003 * Example:
5004 * if { echo foo; } then { echo bar; } fi */
5005 if (ctx->command->group)
5006 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005007 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00005008
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005009 ctx->ctx_res_w = r->res;
5010 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005011 word->o_assignment = r->assignment_flag;
5012
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005013 if (ctx->old_flag & FLAG_END) {
5014 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00005015
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005016 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005017 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005018 old = ctx->stack;
5019 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005020 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005021# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005022 o_addstr(&old->as_string, ctx->as_string.data);
5023 o_free_unsafe(&ctx->as_string);
5024 old->command->group_as_string = xstrdup(old->as_string.data);
5025 debug_printf_parse("pop, remembering as:'%s'\n",
5026 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005027# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005028 *ctx = *old; /* physical copy */
5029 free(old);
5030 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005031 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005032}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005033#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00005034
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005035/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005036 * Normal return is 0. Syntax errors return 1.
5037 * Note: on return, word is reset, but not o_free'd!
5038 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005039static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00005040{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005041 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00005042
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005043 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005044 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005045 debug_printf_parse("done_word return 0: true null, ignored\n");
5046 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005047 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005048
Eric Andersen25f27032001-04-26 23:22:31 +00005049 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005050 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
5051 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005052 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5053 * "2.7 Redirection
5054 * ...the word that follows the redirection operator
5055 * shall be subjected to tilde expansion, parameter expansion,
5056 * command substitution, arithmetic expansion, and quote
5057 * removal. Pathname expansion shall not be performed
5058 * on the word by a non-interactive shell; an interactive
5059 * shell may perform it, but shall do so only when
5060 * the expansion would result in one word."
5061 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005062 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005063 /* Cater for >\file case:
5064 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
5065 * Same with heredocs:
5066 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
5067 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005068 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
5069 unbackslash(ctx->pending_redirect->rd_filename);
5070 /* Is it <<"HEREDOC"? */
5071 if (word->o_quoted) {
5072 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
5073 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005074 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005075 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005076 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00005077 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005078 /* If this word wasn't an assignment, next ones definitely
5079 * can't be assignments. Even if they look like ones. */
5080 if (word->o_assignment != DEFINITELY_ASSIGNMENT
5081 && word->o_assignment != WORD_IS_KEYWORD
5082 ) {
5083 word->o_assignment = NOT_ASSIGNMENT;
5084 } else {
5085 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
5086 command->assignment_cnt++;
5087 word->o_assignment = MAYBE_ASSIGNMENT;
5088 }
5089
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005090#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005091# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00005092 if (ctx->ctx_dsemicolon
5093 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
5094 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00005095 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005096 /* ctx->ctx_res_w = RES_MATCH; */
5097 ctx->ctx_dsemicolon = 0;
5098 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005099# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005100 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005101# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005102 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5103 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005104# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005105# if ENABLE_HUSH_CASE
5106 && ctx->ctx_res_w != RES_CASE
5107# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005108 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005109 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005110 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005111 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005112 debug_printf_parse("done_word return %d\n",
5113 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005114 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005115 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005116# ifdef CMD_SINGLEWORD_NOGLOB_COND
5117 if (strcmp(word->data, "export") == 0
5118# if ENABLE_HUSH_LOCAL
5119 || strcmp(word->data, "local") == 0
5120# endif
5121 ) {
5122 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5123 } else
5124# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005125# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005126 if (strcmp(word->data, "[[") == 0) {
5127 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5128 }
5129 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005130# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005131 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005132#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005133 if (command->group) {
5134 /* "{ echo foo; } echo bar" - bad */
5135 syntax_error_at(word->data);
5136 debug_printf_parse("done_word return 1: syntax error, "
5137 "groups and arglists don't mix\n");
5138 return 1;
5139 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005140 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005141 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5142 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005143 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005144 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005145 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005146 char *p = word->data;
5147 while (p[0] == SPECIAL_VAR_SYMBOL
5148 && (p[1] & 0x7f) == '@'
5149 && p[2] == SPECIAL_VAR_SYMBOL
5150 ) {
5151 p += 3;
5152 }
5153 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005154 /* saw no "$@", or not only "$@" but some
5155 * real text is there too */
5156 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005157 * e.g. "", $empty"" etc to not disappear */
5158 o_addchr(word, SPECIAL_VAR_SYMBOL);
5159 o_addchr(word, SPECIAL_VAR_SYMBOL);
5160 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005161 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005162 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005163 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005164 }
Eric Andersen25f27032001-04-26 23:22:31 +00005165
Denis Vlasenko06810332007-05-21 23:30:54 +00005166#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005167 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005168 if (word->o_quoted
5169 || !is_well_formed_var_name(command->argv[0], '\0')
5170 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005171 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005172 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005173 return 1;
5174 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005175 /* Force FOR to have just one word (variable name) */
5176 /* NB: basically, this makes hush see "for v in ..."
5177 * syntax as if it is "for v; in ...". FOR and IN become
5178 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005179 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005180 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005181#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005182#if ENABLE_HUSH_CASE
5183 /* Force CASE to have just one word */
5184 if (ctx->ctx_res_w == RES_CASE) {
5185 done_pipe(ctx, PIPE_SEQ);
5186 }
5187#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005188
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005189 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005190
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005191 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005192 return 0;
5193}
5194
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005195
5196/* Peek ahead in the input to find out if we have a "&n" construct,
5197 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005198 * Return:
5199 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5200 * REDIRFD_SYNTAX_ERR if syntax error,
5201 * REDIRFD_TO_FILE if no & was seen,
5202 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005203 */
5204#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005205#define parse_redir_right_fd(as_string, input) \
5206 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005207#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005208static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005209{
5210 int ch, d, ok;
5211
5212 ch = i_peek(input);
5213 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005214 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005215
5216 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005217 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005218 ch = i_peek(input);
5219 if (ch == '-') {
5220 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005221 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005222 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005223 }
5224 d = 0;
5225 ok = 0;
5226 while (ch != EOF && isdigit(ch)) {
5227 d = d*10 + (ch-'0');
5228 ok = 1;
5229 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005230 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005231 ch = i_peek(input);
5232 }
5233 if (ok) return d;
5234
5235//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5236
5237 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005238 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005239}
5240
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005241/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005242 */
5243static int parse_redirect(struct parse_context *ctx,
5244 int fd,
5245 redir_type style,
5246 struct in_str *input)
5247{
5248 struct command *command = ctx->command;
5249 struct redir_struct *redir;
5250 struct redir_struct **redirp;
5251 int dup_num;
5252
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005253 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005254 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005255 /* Check for a '>&1' type redirect */
5256 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5257 if (dup_num == REDIRFD_SYNTAX_ERR)
5258 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005259 } else {
5260 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005261 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005262 if (dup_num) { /* <<-... */
5263 ch = i_getch(input);
5264 nommu_addchr(&ctx->as_string, ch);
5265 ch = i_peek(input);
5266 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005267 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005268
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005269 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005270 int ch = i_peek(input);
5271 if (ch == '|') {
5272 /* >|FILE redirect ("clobbering" >).
5273 * Since we do not support "set -o noclobber" yet,
5274 * >| and > are the same for now. Just eat |.
5275 */
5276 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005277 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005278 }
5279 }
5280
5281 /* Create a new redir_struct and append it to the linked list */
5282 redirp = &command->redirects;
5283 while ((redir = *redirp) != NULL) {
5284 redirp = &(redir->next);
5285 }
5286 *redirp = redir = xzalloc(sizeof(*redir));
5287 /* redir->next = NULL; */
5288 /* redir->rd_filename = NULL; */
5289 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005290 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005291
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005292 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5293 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005294
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005295 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005296 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005297 /* Erik had a check here that the file descriptor in question
5298 * is legit; I postpone that to "run time"
5299 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005300 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5301 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005302 } else {
5303 /* Set ctx->pending_redirect, so we know what to do at the
5304 * end of the next parsed word. */
5305 ctx->pending_redirect = redir;
5306 }
5307 return 0;
5308}
5309
Eric Andersen25f27032001-04-26 23:22:31 +00005310/* If a redirect is immediately preceded by a number, that number is
5311 * supposed to tell which file descriptor to redirect. This routine
5312 * looks for such preceding numbers. In an ideal world this routine
5313 * needs to handle all the following classes of redirects...
5314 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5315 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5316 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5317 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005318 *
5319 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5320 * "2.7 Redirection
5321 * ... If n is quoted, the number shall not be recognized as part of
5322 * the redirection expression. For example:
5323 * echo \2>a
5324 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005325 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005326 *
5327 * A -1 return means no valid number was found,
5328 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005329 */
5330static int redirect_opt_num(o_string *o)
5331{
5332 int num;
5333
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005334 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005335 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005336 num = bb_strtou(o->data, NULL, 10);
5337 if (errno || num < 0)
5338 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005339 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005340 return num;
5341}
5342
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005343#if BB_MMU
5344#define fetch_till_str(as_string, input, word, skip_tabs) \
5345 fetch_till_str(input, word, skip_tabs)
5346#endif
5347static char *fetch_till_str(o_string *as_string,
5348 struct in_str *input,
5349 const char *word,
5350 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005351{
5352 o_string heredoc = NULL_O_STRING;
5353 int past_EOL = 0;
5354 int ch;
5355
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005356 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005357 while (1) {
5358 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005359 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005360 if (ch == '\n') {
5361 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5362 heredoc.data[past_EOL] = '\0';
5363 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5364 return heredoc.data;
5365 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005366 do {
5367 o_addchr(&heredoc, ch);
5368 past_EOL = heredoc.length;
5369 jump_in:
5370 do {
5371 ch = i_getch(input);
5372 nommu_addchr(as_string, ch);
5373 } while (skip_tabs && ch == '\t');
5374 } while (ch == '\n');
5375 }
5376 if (ch == EOF) {
5377 o_free_unsafe(&heredoc);
5378 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005379 }
5380 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005381 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005382 }
5383}
5384
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005385/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5386 * and load them all. There should be exactly heredoc_cnt of them.
5387 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005388static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5389{
5390 struct pipe *pi = ctx->list_head;
5391
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005392 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005393 int i;
5394 struct command *cmd = pi->cmds;
5395
5396 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5397 pi->num_cmds,
5398 cmd->argv ? cmd->argv[0] : "NONE");
5399 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005400 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005401
5402 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5403 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005404 while (redir) {
5405 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005406 char *p;
5407
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005408 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005409 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005410 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005411 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005412 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005413 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005414 return 1;
5415 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005416 free(redir->rd_filename);
5417 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005418 heredoc_cnt--;
5419 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005420 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005421 }
5422 cmd++;
5423 }
5424 pi = pi->next;
5425 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005426#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005427 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005428 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005429 bb_error_msg_and_die("heredoc BUG 2");
5430#endif
5431 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005432}
5433
5434
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005435#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005436static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005437{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005438 pid_t pid;
5439 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005440# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005441 char **to_free;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005442# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005443
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005444 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005445 pid = BB_MMU ? fork() : vfork();
5446 if (pid < 0)
5447 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005448
Denis Vlasenko05743d72008-02-10 12:10:08 +00005449 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005450 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005451 /* Process substitution is not considered to be usual
5452 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005453 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5454 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005455 bb_signals(0
5456 + (1 << SIGTSTP)
5457 + (1 << SIGTTIN)
5458 + (1 << SIGTTOU)
5459 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005460 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005461 close(channel[0]); /* NB: close _first_, then move fd! */
5462 xmove_fd(channel[1], 1);
5463 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005464 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005465 /* Awful hack for `trap` or $(trap).
5466 *
5467 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5468 * contains an example where "trap" is executed in a subshell:
5469 *
5470 * save_traps=$(trap)
5471 * ...
5472 * eval "$save_traps"
5473 *
5474 * Standard does not say that "trap" in subshell shall print
5475 * parent shell's traps. It only says that its output
5476 * must have suitable form, but then, in the above example
5477 * (which is not supposed to be normative), it implies that.
5478 *
5479 * bash (and probably other shell) does implement it
5480 * (traps are reset to defaults, but "trap" still shows them),
5481 * but as a result, "trap" logic is hopelessly messed up:
5482 *
5483 * # trap
5484 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5485 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5486 * # true | trap <--- trap is in subshell - no output (ditto)
5487 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5488 * trap -- 'echo Ho' SIGWINCH
5489 * # echo `(trap)` <--- in subshell in subshell - output
5490 * trap -- 'echo Ho' SIGWINCH
5491 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5492 * trap -- 'echo Ho' SIGWINCH
5493 *
5494 * The rules when to forget and when to not forget traps
5495 * get really complex and nonsensical.
5496 *
5497 * Our solution: ONLY bare $(trap) or `trap` is special.
5498 */
5499 s = skip_whitespace(s);
5500 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5501 {
5502 static const char *const argv[] = { NULL, NULL };
5503 builtin_trap((char**)argv);
5504 exit(0); /* not _exit() - we need to fflush */
5505 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005506# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005507 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005508 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005509 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005510# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005511 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005512 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5513 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005514 * echo OK
5515 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005516 re_execute_shell(&to_free,
5517 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005518 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005519 G.global_argv + 1,
5520 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005521# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005522 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005523
5524 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005525 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005526# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005527 G.count_SIGCHLD++;
5528//bb_error_msg("[%d] fork in generate_stream_from_string: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005529# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005530 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005531# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005532 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005533# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005534 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005535 close_on_exec_on(channel[0]);
5536 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005537}
5538
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005539/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005540static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005541{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005542 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005543 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005544 pid_t pid;
5545 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005546
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005547 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005548
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005549 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005550 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005551 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005552 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005553 if (ch == '\n') {
5554 eol_cnt++;
5555 continue;
5556 }
5557 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005558 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005559 eol_cnt--;
5560 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005561 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005562 }
5563
Denys Vlasenko647553a2009-11-15 19:58:19 +01005564 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005565 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005566 /* We need to extract exitcode. Test case
5567 * "true; echo `sleep 1; false` $?"
5568 * should print 1 */
5569 safe_waitpid(pid, &status, 0);
5570 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5571 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005572}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005573#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005574
Denys Vlasenkoc2704542009-11-20 19:14:19 +01005575#if !ENABLE_HUSH_FUNCTIONS
5576#define parse_group(dest, ctx, input, ch) \
5577 parse_group(ctx, input, ch)
5578#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005579static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005580 struct in_str *input, int ch)
5581{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005582 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005583 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005584 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005585 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005586 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005587 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005588
5589 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005590#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005591 if (ch == '(' && !dest->o_quoted) {
5592 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005593 if (done_word(dest, ctx))
5594 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005595 if (!command->argv)
5596 goto skip; /* (... */
5597 if (command->argv[1]) { /* word word ... (... */
5598 syntax_error_unexpected_ch('(');
5599 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005600 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005601 /* it is "word(..." or "word (..." */
5602 do
5603 ch = i_getch(input);
5604 while (ch == ' ' || ch == '\t');
5605 if (ch != ')') {
5606 syntax_error_unexpected_ch(ch);
5607 return 1;
5608 }
5609 nommu_addchr(&ctx->as_string, ch);
5610 do
5611 ch = i_getch(input);
5612 while (ch == ' ' || ch == '\t' || ch == '\n');
5613 if (ch != '{') {
5614 syntax_error_unexpected_ch(ch);
5615 return 1;
5616 }
5617 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005618 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005619 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005620 }
5621#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005622
5623#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005624 if (command->argv /* word [word]{... */
5625 || dest->length /* word{... */
5626 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005627 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005628 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005629 debug_printf_parse("parse_group return 1: "
5630 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005631 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005632 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005633#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005634
5635#if ENABLE_HUSH_FUNCTIONS
5636 skip:
5637#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005638 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005639 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005640 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005641 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005642 } else {
5643 /* bash does not allow "{echo...", requires whitespace */
5644 ch = i_getch(input);
5645 if (ch != ' ' && ch != '\t' && ch != '\n') {
5646 syntax_error_unexpected_ch(ch);
5647 return 1;
5648 }
5649 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005650 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005651
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005652 {
5653#if !BB_MMU
5654 char *as_string = NULL;
5655#endif
5656 pipe_list = parse_stream(&as_string, input, endch);
5657#if !BB_MMU
5658 if (as_string)
5659 o_addstr(&ctx->as_string, as_string);
5660#endif
5661 /* empty ()/{} or parse error? */
5662 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005663 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005664#if !BB_MMU
5665 free(as_string);
5666#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005667 debug_printf_parse("parse_group return 1: "
5668 "parse_stream returned %p\n", pipe_list);
5669 return 1;
5670 }
5671 command->group = pipe_list;
5672#if !BB_MMU
5673 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5674 command->group_as_string = as_string;
5675 debug_printf_parse("end of group, remembering as:'%s'\n",
5676 command->group_as_string);
5677#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005678 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005679 debug_printf_parse("parse_group return 0\n");
5680 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005681 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005682}
5683
Mike Frysinger98c52642009-04-02 10:02:37 +00005684#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005685/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005686static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005687/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005688static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005689{
5690 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005691 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005692 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005693 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005694 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005695 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005696 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005697 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005698 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005699 }
5700}
5701/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005702static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005703{
5704 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005705 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005706 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005707 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005708 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005709 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005710 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005711 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005712 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005713 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005714 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005715 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005716 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005717 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005718 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005719 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005720 continue;
5721 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005722 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005723 }
5724}
5725/* Process `cmd` - copy contents until "`" is seen. Complicated by
5726 * \` quoting.
5727 * "Within the backquoted style of command substitution, backslash
5728 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5729 * The search for the matching backquote shall be satisfied by the first
5730 * backquote found without a preceding backslash; during this search,
5731 * if a non-escaped backquote is encountered within a shell comment,
5732 * a here-document, an embedded command substitution of the $(command)
5733 * form, or a quoted string, undefined results occur. A single-quoted
5734 * or double-quoted string that begins, but does not end, within the
5735 * "`...`" sequence produces undefined results."
5736 * Example Output
5737 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5738 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005739static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005740{
5741 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005742 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005743 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005744 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005745 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005746 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005747 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005748 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005749 if (ch == '\\') {
5750 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005751 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005752 if (ch2 == 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 Vlasenko5c090a92009-04-08 21:51:33 +00005755 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005756 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005757 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005758 ch = ch2;
5759 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005760 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005761 }
5762}
5763/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5764 * quoting and nested ()s.
5765 * "With the $(command) style of command substitution, all characters
5766 * following the open parenthesis to the matching closing parenthesis
5767 * constitute the command. Any valid shell script can be used for command,
5768 * except a script consisting solely of redirections which produces
5769 * unspecified results."
5770 * Example Output
5771 * echo $(echo '(TEST)' BEST) (TEST) BEST
5772 * echo $(echo 'TEST)' BEST) TEST) BEST
5773 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5774 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005775static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005776{
5777 int count = 0;
5778 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005779 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005780 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005781 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005782 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005783 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005784 if (ch == '(')
5785 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005786 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005787 if (--count < 0) {
5788 if (!dbl)
5789 break;
5790 if (i_peek(input) == ')') {
5791 i_getch(input);
5792 break;
5793 }
5794 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005795 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005796 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005797 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005798 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005799 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005800 continue;
5801 }
5802 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005803 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005804 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005805 continue;
5806 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005807 if (ch == '\\') {
5808 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005809 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005810 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005811 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005812 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005813 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005814 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005815 continue;
5816 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005817 }
5818}
Mike Frysinger98c52642009-04-02 10:02:37 +00005819#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005820
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005821/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005822#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005823#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005824 handle_dollar(dest, input)
5825#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005826static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005827 o_string *dest,
5828 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005829{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005830 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005831 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005832
5833 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005834 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005835 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005836 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005837 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005838 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005839 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005840 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005841 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005842 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005843 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005844 if (!isalnum(ch) && ch != '_')
5845 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005846 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005847 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005848 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005849 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005850 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005851 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005852 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005853 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005854 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005855 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005856 o_addchr(dest, ch | quote_mask);
5857 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005858 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005859 case '$': /* pid */
5860 case '!': /* last bg pid */
5861 case '?': /* last exit code */
5862 case '#': /* number of args */
5863 case '*': /* args */
5864 case '@': /* args */
5865 goto make_one_char_var;
5866 case '{': {
5867 bool first_char, all_digits;
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005868 int expansion;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005869
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005870 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005871 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005872 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5873
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005874 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005875 expansion = 0;
5876 first_char = true;
5877 all_digits = false;
5878 while (1) {
5879 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005880 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005881 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005882 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005883 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005884
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005885 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005886 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005887 /* ${#var}: length of var contents */
5888 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005889 }
5890 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005891 all_digits = true;
5892 goto char_ok;
5893 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005894 /* They're being verbose and doing ${?} */
5895 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5896 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005897 }
5898
5899 if (expansion < 2
5900 && ( (all_digits && !isdigit(ch))
5901 || (!all_digits && !isalnum(ch) && ch != '_')
5902 )
5903 ) {
5904 /* handle parameter expansions
5905 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5906 */
5907 if (first_char)
5908 goto case_default;
5909 switch (ch) {
5910 case ':': /* null modifier */
5911 if (expansion == 0) {
5912 debug_printf_parse(": null modifier\n");
5913 ++expansion;
5914 break;
5915 }
5916 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005917 case '#': /* remove prefix */
5918 case '%': /* remove suffix */
5919 if (expansion == 0) {
5920 debug_printf_parse(": remove suffix/prefix\n");
5921 expansion = 2;
5922 break;
5923 }
5924 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005925 case '-': /* default value */
5926 case '=': /* assign default */
5927 case '+': /* alternative */
5928 case '?': /* error indicate */
5929 debug_printf_parse(": parameter expansion\n");
5930 expansion = 2;
5931 break;
5932 default:
5933 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005934 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005935 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5936 return 1;
5937 }
5938 }
5939 char_ok:
5940 debug_printf_parse(": '%c'\n", ch);
5941 o_addchr(dest, ch | quote_mask);
5942 quote_mask = 0;
5943 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005944 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005945 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5946 break;
5947 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005948#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005949 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005950# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005951 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005952# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005953 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005954 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005955# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005956 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005957 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005958 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005959 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5960 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005961# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005962 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005963# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005964 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005965# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005966 if (as_string) {
5967 o_addstr(as_string, dest->data + pos);
5968 o_addchr(as_string, ')');
5969 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005970 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005971# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005972 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005973 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005974 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005975# endif
5976# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005977 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5978 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005979# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005980 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005981# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005982 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005983# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005984 if (as_string) {
5985 o_addstr(as_string, dest->data + pos);
5986 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005987 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005988# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005989 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005990# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005991 break;
5992 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005993#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005994 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005995 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005996 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005997 ch = i_peek(input);
5998 if (isalnum(ch)) { /* it's $_name or $_123 */
5999 ch = '_';
6000 goto make_var;
6001 }
6002 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02006003 /* TODO: $_ and $-: */
6004 /* $_ Shell or shell script name; or last argument of last command
6005 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
6006 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006007 /* $- Option flags set by set builtin or shell options (-i etc) */
6008 default:
6009 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00006010 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00006011 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00006012 return 0;
6013}
6014
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006015#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006016#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006017 parse_stream_dquoted(dest, input, dquote_end)
6018#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006019static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006020 o_string *dest,
6021 struct in_str *input,
6022 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006023{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006024 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006025 int next;
6026
6027 again:
6028 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006029 if (ch != EOF)
6030 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006031 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006032 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006033 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006034 debug_printf_parse("parse_stream_dquoted return 0\n");
6035 return 0;
6036 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006037 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006038 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006039 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006040 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006041 }
6042 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006043 if (ch != '\n') {
6044 next = i_peek(input);
6045 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006046 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006047 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006048 if (ch == '\\') {
6049 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006050 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006051 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006052 }
6053 /* bash:
6054 * "The backslash retains its special meaning [in "..."]
6055 * only when followed by one of the following characters:
6056 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006057 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006058 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006059 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00006060 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006061 if (ch != '\n') {
6062 o_addqchr(dest, ch);
6063 nommu_addchr(as_string, ch);
6064 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006065 } else {
6066 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00006067 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006068 }
6069 goto again;
6070 }
6071 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006072 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006073 debug_printf_parse("parse_stream_dquoted return 1: "
6074 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006075 return 1;
6076 }
6077 goto again;
6078 }
6079#if ENABLE_HUSH_TICK
6080 if (ch == '`') {
6081 //int pos = dest->length;
6082 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6083 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006084 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006085 o_addchr(dest, SPECIAL_VAR_SYMBOL);
6086 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00006087 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006088 }
6089#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00006090 o_addQchr(dest, ch);
6091 if (ch == '='
6092 && (dest->o_assignment == MAYBE_ASSIGNMENT
6093 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006094 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00006095 ) {
6096 dest->o_assignment = DEFINITELY_ASSIGNMENT;
6097 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006098 goto again;
6099}
6100
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006101/*
6102 * Scan input until EOF or end_trigger char.
6103 * Return a list of pipes to execute, or NULL on EOF
6104 * or if end_trigger character is met.
6105 * On syntax error, exit is shell is not interactive,
6106 * reset parsing machinery and start parsing anew,
6107 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006108 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006109static struct pipe *parse_stream(char **pstring,
6110 struct in_str *input,
6111 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006112{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006113 struct parse_context ctx;
6114 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006115 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006116 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006117
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006118 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006119 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006120 * found. When recursing, quote state is passed in via dest->o_escape.
6121 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006122 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006123 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006124 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006125
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006126 /* If very first arg is "" or '', dest.data may end up NULL.
6127 * Preventing this: */
6128 o_addchr(&dest, '\0');
6129 dest.length = 0;
6130
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006131 G.ifs = get_local_var_value("IFS");
6132 if (G.ifs == NULL)
6133 G.ifs = " \t\n";
6134
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006135 reset:
6136#if ENABLE_HUSH_INTERACTIVE
6137 input->promptmode = 0; /* PS1 */
6138#endif
6139 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6140 initialize_context(&ctx);
6141 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006142 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006143 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006144 const char *is_ifs;
6145 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006146 int ch;
6147 int next;
6148 int redir_fd;
6149 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006150
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006151 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006152 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006153 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006154 goto parse_error;
6155 }
6156 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006157 is_in_dquote = 0;
6158 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006159 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006160 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6161 ch, ch, dest.o_escape);
6162 if (ch == EOF) {
6163 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006164
6165 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006166 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006167 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006168 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006169 /* end_trigger == '}' case errors out earlier,
6170 * checking only ')' */
6171 if (end_trigger == ')') {
6172 syntax_error_unterm_ch('('); /* exits */
6173 /* goto parse_error; */
6174 }
6175
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006176 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006177 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006178 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006179 o_free(&dest);
6180 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006181 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006182 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006183 /* (this makes bare "&" cmd a no-op.
6184 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006185 if (pi->num_cmds == 0
6186 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6187 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006188 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006189 pi = NULL;
6190 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006191#if !BB_MMU
6192 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6193 if (pstring)
6194 *pstring = ctx.as_string.data;
6195 else
6196 o_free_unsafe(&ctx.as_string);
6197#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006198 debug_leave();
6199 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006200 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006201 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006202 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006203
6204 next = '\0';
6205 if (ch != '\n')
6206 next = i_peek(input);
6207
6208 is_special = "{}<>;&|()#'" /* special outside of "str" */
6209 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6210 /* Are { and } special here? */
6211 if (ctx.command->argv /* word [word]{... */
6212 || dest.length /* word{... */
6213 || dest.o_quoted /* ""{... */
6214 || (next != ';' && next != ')' && !strchr(G.ifs, next)) /* {word */
6215 ) {
6216 /* They are not special, skip "{}" */
6217 is_special += 2;
6218 }
6219 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006220 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006221
6222 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006223 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006224 o_addQchr(&dest, ch);
6225 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6226 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006227 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006228 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006229 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006230 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006231 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006232 continue;
6233 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006234
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006235 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006236 if (done_word(&dest, &ctx)) {
6237 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006238 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006239 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006240#if ENABLE_HUSH_CASE
6241 /* "case ... in <newline> word) ..." -
6242 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006243 if (ctx.command->argv == NULL
6244 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006245 ) {
6246 continue;
6247 }
6248#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006249 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006250 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006251 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6252 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006253 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006254 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006255 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006256 heredoc_cnt = 0;
6257 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006258 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006259 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006260 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006261 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006262 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006263 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006264
6265 /* "cmd}" or "cmd }..." without semicolon or &:
6266 * } is an ordinary char in this case, even inside { cmd; }
6267 * Pathological example: { ""}; } should exec "}" cmd
6268 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006269 if (ch == '}') {
6270 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6271 || dest.length != 0 /* word} */
6272 || dest.o_quoted /* ""} */
6273 ) {
6274 goto ordinary_char;
6275 }
6276 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6277 goto skip_end_trigger;
6278 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006279 }
6280
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006281 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006282 && (ch != ';' || heredoc_cnt == 0)
6283#if ENABLE_HUSH_CASE
6284 && (ch != ')'
6285 || ctx.ctx_res_w != RES_MATCH
6286 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6287 )
6288#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006289 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006290 if (heredoc_cnt) {
6291 /* This is technically valid:
6292 * { cat <<HERE; }; echo Ok
6293 * heredoc
6294 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006295 * HERE
6296 * but we don't support this.
6297 * We require heredoc to be in enclosing {}/(),
6298 * if any.
6299 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006300 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006301 goto parse_error;
6302 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006303 if (done_word(&dest, &ctx)) {
6304 goto parse_error;
6305 }
6306 done_pipe(&ctx, PIPE_SEQ);
6307 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006308 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006309 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006310 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006311 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006312 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006313#if !BB_MMU
6314 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6315 if (pstring)
6316 *pstring = ctx.as_string.data;
6317 else
6318 o_free_unsafe(&ctx.as_string);
6319#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006320 debug_leave();
6321 debug_printf_parse("parse_stream return %p: "
6322 "end_trigger char found\n",
6323 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006324 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006325 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006326 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006327 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006328 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006329 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006330
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006331 /* Catch <, > before deciding whether this word is
6332 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6333 switch (ch) {
6334 case '>':
6335 redir_fd = redirect_opt_num(&dest);
6336 if (done_word(&dest, &ctx)) {
6337 goto parse_error;
6338 }
6339 redir_style = REDIRECT_OVERWRITE;
6340 if (next == '>') {
6341 redir_style = REDIRECT_APPEND;
6342 ch = i_getch(input);
6343 nommu_addchr(&ctx.as_string, ch);
6344 }
6345#if 0
6346 else if (next == '(') {
6347 syntax_error(">(process) not supported");
6348 goto parse_error;
6349 }
6350#endif
6351 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6352 goto parse_error;
6353 continue; /* back to top of while (1) */
6354 case '<':
6355 redir_fd = redirect_opt_num(&dest);
6356 if (done_word(&dest, &ctx)) {
6357 goto parse_error;
6358 }
6359 redir_style = REDIRECT_INPUT;
6360 if (next == '<') {
6361 redir_style = REDIRECT_HEREDOC;
6362 heredoc_cnt++;
6363 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6364 ch = i_getch(input);
6365 nommu_addchr(&ctx.as_string, ch);
6366 } else if (next == '>') {
6367 redir_style = REDIRECT_IO;
6368 ch = i_getch(input);
6369 nommu_addchr(&ctx.as_string, ch);
6370 }
6371#if 0
6372 else if (next == '(') {
6373 syntax_error("<(process) not supported");
6374 goto parse_error;
6375 }
6376#endif
6377 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6378 goto parse_error;
6379 continue; /* back to top of while (1) */
6380 }
6381
6382 if (dest.o_assignment == MAYBE_ASSIGNMENT
6383 /* check that we are not in word in "a=1 2>word b=1": */
6384 && !ctx.pending_redirect
6385 ) {
6386 /* ch is a special char and thus this word
6387 * cannot be an assignment */
6388 dest.o_assignment = NOT_ASSIGNMENT;
6389 }
6390
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006391 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6392
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006393 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006394 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006395 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006396 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006397 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006398 if (ch == EOF || ch == '\n')
6399 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006400 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006401 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006402 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006403 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006404 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006405 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006406 }
6407 break;
6408 case '\\':
6409 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006410 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006411 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006412 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006413 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006414 if (ch != '\n') {
6415 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006416 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006417 o_addchr(&dest, ch);
6418 nommu_addchr(&ctx.as_string, ch);
6419 /* Example: echo Hello \2>file
6420 * we need to know that word 2 is quoted */
6421 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006422 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006423#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006424 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006425 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6426 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006427 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006428#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006429 break;
6430 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006431 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006432 debug_printf_parse("parse_stream parse error: "
6433 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006434 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006435 }
Eric Andersen25f27032001-04-26 23:22:31 +00006436 break;
6437 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006438 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006439 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006440 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006441 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006442 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006443 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006444 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006445 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006446 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006447 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006448 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006449 }
Eric Andersen25f27032001-04-26 23:22:31 +00006450 break;
6451 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006452 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006453 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006454 if (dest.o_assignment == NOT_ASSIGNMENT)
6455 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006456 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006457#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006458 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006459#if !BB_MMU
6460 int pos;
6461#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006462 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6463 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006464#if !BB_MMU
6465 pos = dest.length;
6466#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006467 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006468#if !BB_MMU
6469 o_addstr(&ctx.as_string, dest.data + pos);
6470 o_addchr(&ctx.as_string, '`');
6471#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006472 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6473 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006474 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006475 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006476#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006477 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006478#if ENABLE_HUSH_CASE
6479 case_semi:
6480#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006481 if (done_word(&dest, &ctx)) {
6482 goto parse_error;
6483 }
6484 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006485#if ENABLE_HUSH_CASE
6486 /* Eat multiple semicolons, detect
6487 * whether it means something special */
6488 while (1) {
6489 ch = i_peek(input);
6490 if (ch != ';')
6491 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006492 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006493 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006494 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006495 ctx.ctx_dsemicolon = 1;
6496 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006497 break;
6498 }
6499 }
6500#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006501 new_cmd:
6502 /* We just finished a cmd. New one may start
6503 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006504 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006505 break;
6506 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006507 if (done_word(&dest, &ctx)) {
6508 goto parse_error;
6509 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006510 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006511 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006512 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006513 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006514 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006515 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006516 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006517 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006518 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006519 if (done_word(&dest, &ctx)) {
6520 goto parse_error;
6521 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006522#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006523 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006524 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006525#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006526 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006527 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006528 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006529 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006530 } else {
6531 /* we could pick up a file descriptor choice here
6532 * with redirect_opt_num(), but bash doesn't do it.
6533 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006534 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00006535 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006536 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006537 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006538#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006539 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006540 if (ctx.ctx_res_w == RES_MATCH
6541 && ctx.command->argv == NULL /* not (word|(... */
6542 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006543 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006544 ) {
6545 continue;
6546 }
6547#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006548 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006549 if (parse_group(&dest, &ctx, input, ch) != 0) {
6550 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006551 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006552 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006553 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006554#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006555 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006556 goto case_semi;
6557#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006558 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006559 /* proper use of this character is caught by end_trigger:
6560 * if we see {, we call parse_group(..., end_trigger='}')
6561 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006562 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006563 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006564 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006565 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006566 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006567 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006568 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006569
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006570 parse_error:
6571 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006572 struct parse_context *pctx;
6573 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006574
6575 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006576 * Sample for finding leaks on syntax error recovery path.
6577 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006578 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006579 * Samples to catch leaks at execution:
6580 * while if (true | {true;}); then echo ok; fi; do break; done
6581 * 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 +00006582 */
6583 pctx = &ctx;
6584 do {
6585 /* Update pipe/command counts,
6586 * otherwise freeing may miss some */
6587 done_pipe(pctx, PIPE_SEQ);
6588 debug_printf_clean("freeing list %p from ctx %p\n",
6589 pctx->list_head, pctx);
6590 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006591 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006592 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006593#if !BB_MMU
6594 o_free_unsafe(&pctx->as_string);
6595#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006596 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006597 if (pctx != &ctx) {
6598 free(pctx);
6599 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006600 IF_HAS_KEYWORDS(pctx = p2;)
6601 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006602 /* Free text, clear all dest fields */
6603 o_free(&dest);
6604 /* If we are not in top-level parse, we return,
6605 * our caller will propagate error.
6606 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006607 if (end_trigger != ';') {
6608#if !BB_MMU
6609 if (pstring)
6610 *pstring = NULL;
6611#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006612 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006613 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006614 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006615 /* Discard cached input, force prompt */
6616 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006617 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006618 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006619 }
Eric Andersen25f27032001-04-26 23:22:31 +00006620}
6621
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006622/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006623 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6624 * end_trigger controls how often we stop parsing
6625 * NUL: parse all, execute, return
6626 * ';': parse till ';' or newline, execute, repeat till EOF
6627 */
6628static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006629{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006630 /* Why we need empty flag?
6631 * An obscure corner case "false; ``; echo $?":
6632 * empty command in `` should still set $? to 0.
6633 * But we can't just set $? to 0 at the start,
6634 * this breaks "false; echo `echo $?`" case.
6635 */
6636 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006637 while (1) {
6638 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006639
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006640 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006641 if (!pipe_list) { /* EOF */
6642 if (empty)
6643 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006644 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006645 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006646 debug_print_tree(pipe_list, 0);
6647 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6648 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006649 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006650 }
Eric Andersen25f27032001-04-26 23:22:31 +00006651}
6652
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006653static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006654{
6655 struct in_str input;
6656 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006657 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006658}
6659
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006660static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006661{
Eric Andersen25f27032001-04-26 23:22:31 +00006662 struct in_str input;
6663 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006664 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006665}
6666
Denis Vlasenkof9375282009-04-05 19:13:39 +00006667/* Called a few times only (or even once if "sh -c") */
6668static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006669{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006670 unsigned sig;
6671 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006672
Denis Vlasenkof9375282009-04-05 19:13:39 +00006673 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006674 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006675 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006676 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006677 mask |= SPECIAL_JOB_SIGS;
6678 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006679 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006680
Denis Vlasenkof9375282009-04-05 19:13:39 +00006681 if (!second_time)
6682 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6683 sig = 0;
6684 while (mask) {
6685 if (mask & 1)
6686 sigaddset(&G.blocked_set, sig);
6687 mask >>= 1;
6688 sig++;
6689 }
6690 sigdelset(&G.blocked_set, SIGCHLD);
6691
6692 sigprocmask(SIG_SETMASK, &G.blocked_set,
6693 second_time ? NULL : &G.inherited_set);
6694 /* POSIX allows shell to re-enable SIGCHLD
6695 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006696#if ENABLE_HUSH_FAST
6697 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006698 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006699 signal(SIGCHLD, SIGCHLD_handler);
6700#else
6701 if (!second_time)
6702 signal(SIGCHLD, SIG_DFL);
6703#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006704}
6705
6706#if ENABLE_HUSH_JOB
6707/* helper */
6708static void maybe_set_to_sigexit(int sig)
6709{
6710 void (*handler)(int);
6711 /* non_DFL_mask'ed signals are, well, masked,
6712 * no need to set handler for them.
6713 */
6714 if (!((G.non_DFL_mask >> sig) & 1)) {
6715 handler = signal(sig, sigexit);
6716 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6717 signal(sig, handler);
6718 }
6719}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006720/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006721static void set_fatal_handlers(void)
6722{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006723 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006724 if (HUSH_DEBUG) {
6725 maybe_set_to_sigexit(SIGILL );
6726 maybe_set_to_sigexit(SIGFPE );
6727 maybe_set_to_sigexit(SIGBUS );
6728 maybe_set_to_sigexit(SIGSEGV);
6729 maybe_set_to_sigexit(SIGTRAP);
6730 } /* else: hush is perfect. what SEGV? */
6731 maybe_set_to_sigexit(SIGABRT);
6732 /* bash 3.2 seems to handle these just like 'fatal' ones */
6733 maybe_set_to_sigexit(SIGPIPE);
6734 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006735 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006736 * if we aren't interactive... but in this case
6737 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006738 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006739 /*maybe_set_to_sigexit(SIGTERM);*/
6740 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006741}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006742#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006743
Denis Vlasenkod5762932009-03-31 11:22:57 +00006744static int set_mode(const char cstate, const char mode)
6745{
6746 int state = (cstate == '-' ? 1 : 0);
6747 switch (mode) {
6748 case 'n': G.fake_mode = state; break;
6749 case 'x': /*G.debug_mode = state;*/ break;
6750 default: return EXIT_FAILURE;
6751 }
6752 return EXIT_SUCCESS;
6753}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006754
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006755int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006756int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006757{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006758 static const struct variable const_shell_ver = {
6759 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006760 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006761 .max_len = 1, /* 0 can provoke free(name) */
6762 .flg_export = 1,
6763 .flg_read_only = 1,
6764 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006765 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006766 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006767 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006768 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006769 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006770
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006771 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006772 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006773 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006774#if !BB_MMU
6775 G.argv0_for_re_execing = argv[0];
6776#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006777 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006778 G.shell_ver = const_shell_ver; /* copying struct here */
6779 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006780 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006781 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6782 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006783 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006784 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006785 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006786 if (e) while (*e) {
6787 char *value = strchr(*e, '=');
6788 if (value) { /* paranoia */
6789 cur_var->next = xzalloc(sizeof(*cur_var));
6790 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006791 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006792 cur_var->max_len = strlen(*e);
6793 cur_var->flg_export = 1;
6794 }
6795 e++;
6796 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006797 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006798 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006799 putenv((char *)hush_version_str);
6800
6801 /* Export PWD */
6802 set_pwd_var(/*exp:*/ 1);
6803 /* bash also exports SHLVL and _,
6804 * and sets (but doesn't export) the following variables:
6805 * BASH=/bin/bash
6806 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6807 * BASH_VERSION='3.2.0(1)-release'
6808 * HOSTTYPE=i386
6809 * MACHTYPE=i386-pc-linux-gnu
6810 * OSTYPE=linux-gnu
6811 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02006812 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02006813 * EUID=<NNNNN>
6814 * UID=<NNNNN>
6815 * GROUPS=()
6816 * LINES=<NNN>
6817 * COLUMNS=<NNN>
6818 * BASH_ARGC=()
6819 * BASH_ARGV=()
6820 * BASH_LINENO=()
6821 * BASH_SOURCE=()
6822 * DIRSTACK=()
6823 * PIPESTATUS=([0]="0")
6824 * HISTFILE=/<xxx>/.bash_history
6825 * HISTFILESIZE=500
6826 * HISTSIZE=500
6827 * MAILCHECK=60
6828 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6829 * SHELL=/bin/bash
6830 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6831 * TERM=dumb
6832 * OPTERR=1
6833 * OPTIND=1
6834 * IFS=$' \t\n'
6835 * PS1='\s-\v\$ '
6836 * PS2='> '
6837 * PS4='+ '
6838 */
6839
Denis Vlasenko38f63192007-01-22 09:03:07 +00006840#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006841 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006842#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006843 G.global_argc = argc;
6844 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006845 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006846 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006847
Denis Vlasenkoed782372009-04-10 00:45:02 +00006848 if (setjmp(die_jmp)) {
6849 /* xfunc has failed! die die die */
6850 /* no EXIT traps, this is an escape hatch! */
6851 G.exiting = 1;
6852 hush_exit(xfunc_error_retval);
6853 }
6854
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006855 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006856 * block_signals(0) if we are going to execute "sh <script>",
6857 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006858 * If we later decide that we are interactive, we run block_signals(0)
6859 * (or re-run block_signals(1) if we ran block_signals(0) before)
6860 * in order to intercept (more) signals.
6861 */
6862
6863 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006864 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006865 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006866 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006867 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006868#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006869 "<:$:R:V:"
6870# if ENABLE_HUSH_FUNCTIONS
6871 "F:"
6872# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006873#endif
6874 );
6875 if (opt <= 0)
6876 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006877 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006878 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006879 /* Possibilities:
6880 * sh ... -c 'script'
6881 * sh ... -c 'script' ARG0 [ARG1...]
6882 * On NOMMU, if builtin_argc != 0,
6883 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6884 * "" needs to be replaced with NULL
6885 * and BARGV vector fed to builtin function.
6886 * Note: this form never happens:
6887 * sh ... -c 'builtin' [BARGV...] ""
6888 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02006889 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006890 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006891 G.root_ppid = getppid();
6892 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006893 G.global_argv = argv + optind;
6894 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006895 if (builtin_argc) {
6896 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6897 const struct built_in_command *x;
6898
6899 block_signals(0); /* 0: called 1st time */
6900 x = find_builtin(optarg);
6901 if (x) { /* paranoia */
6902 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6903 G.global_argv += builtin_argc;
6904 G.global_argv[-1] = NULL; /* replace "" */
6905 G.last_exitcode = x->function(argv + optind - 1);
6906 }
6907 goto final_return;
6908 }
6909 if (!G.global_argv[0]) {
6910 /* -c 'script' (no params): prevent empty $0 */
6911 G.global_argv--; /* points to argv[i] of 'script' */
6912 G.global_argv[0] = argv[0];
6913 G.global_argc--;
6914 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006915 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006916 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006917 goto final_return;
6918 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006919 /* Well, we cannot just declare interactiveness,
6920 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006921 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006922 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006923 case 's':
6924 /* "-s" means "read from stdin", but this is how we always
6925 * operate, so simply do nothing here. */
6926 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006927#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006928 case '<': /* "big heredoc" support */
6929 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6930 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006931 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006932 G.root_pid = bb_strtou(optarg, &optarg, 16);
6933 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02006934 G.root_ppid = bb_strtou(optarg, &optarg, 16);
6935 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006936 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6937 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006938 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006939 optarg++;
6940 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006941# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006942 optarg++;
6943 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006944# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006945 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006946 case 'R':
6947 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02006948 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006949 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006950# if ENABLE_HUSH_FUNCTIONS
6951 case 'F': {
6952 struct function *funcp = new_function(optarg);
6953 /* funcp->name is already set to optarg */
6954 /* funcp->body is set to NULL. It's a special case. */
6955 funcp->body_as_string = argv[optind];
6956 optind++;
6957 break;
6958 }
6959# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006960#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006961 case 'n':
6962 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006963 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006964 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006965 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006966#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006967 fprintf(stderr, "Usage: sh [FILE]...\n"
6968 " or: sh -c command [args]...\n\n");
6969 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006970#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006971 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006972#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006973 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006974 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006975
Denys Vlasenkodea47882009-10-09 15:40:49 +02006976 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006977 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006978 G.root_ppid = getppid();
6979 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006980
6981 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006982 if (argv[0] && argv[0][0] == '-') {
6983 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006984 debug_printf("sourcing /etc/profile\n");
6985 input = fopen_for_read("/etc/profile");
6986 if (input != NULL) {
6987 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006988 block_signals(0); /* 0: called 1st time */
6989 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006990 parse_and_run_file(input);
6991 fclose(input);
6992 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006993 /* bash: after sourcing /etc/profile,
6994 * tries to source (in the given order):
6995 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006996 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006997 * bash also sources ~/.bash_logout on exit.
6998 * If called as sh, skips .bash_XXX files.
6999 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00007000 }
7001
Denis Vlasenkof9375282009-04-05 19:13:39 +00007002 if (argv[optind]) {
7003 FILE *input;
7004 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00007005 * "bash <script>" (which is never interactive (unless -i?))
7006 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00007007 * If called as sh, does the same but with $ENV.
7008 */
7009 debug_printf("running script '%s'\n", argv[optind]);
7010 G.global_argv = argv + optind;
7011 G.global_argc = argc - optind;
7012 input = xfopen_for_read(argv[optind]);
7013 close_on_exec_on(fileno(input));
7014 if (!signal_mask_is_inited)
7015 block_signals(0); /* 0: called 1st time */
7016 parse_and_run_file(input);
7017#if ENABLE_FEATURE_CLEAN_UP
7018 fclose(input);
7019#endif
7020 goto final_return;
7021 }
7022
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00007023 /* Up to here, shell was non-interactive. Now it may become one.
7024 * NB: don't forget to (re)run block_signals(0/1) as needed.
7025 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007026
Denys Vlasenko28a105d2009-06-01 11:26:30 +02007027 /* A shell is interactive if the '-i' flag was given,
7028 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00007029 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00007030 * no arguments remaining or the -s flag given
7031 * standard input is a terminal
7032 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00007033 * Refer to Posix.2, the description of the 'sh' utility.
7034 */
7035#if ENABLE_HUSH_JOB
7036 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04007037 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
7038 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
7039 if (G_saved_tty_pgrp < 0)
7040 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007041
7042 /* try to dup stdin to high fd#, >= 255 */
7043 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7044 if (G_interactive_fd < 0) {
7045 /* try to dup to any fd */
7046 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007047 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007048 /* give up */
7049 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04007050 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00007051 }
7052 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007053// TODO: track & disallow any attempts of user
7054// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00007055 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007056 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007057 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007058 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007059
Mike Frysinger38478a62009-05-20 04:48:06 -04007060 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007061 /* If we were run as 'hush &', sleep until we are
7062 * in the foreground (tty pgrp == our pgrp).
7063 * If we get started under a job aware app (like bash),
7064 * make sure we are now in charge so we don't fight over
7065 * who gets the foreground */
7066 while (1) {
7067 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04007068 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
7069 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007070 break;
7071 /* send TTIN to ourself (should stop us) */
7072 kill(- shell_pgrp, SIGTTIN);
7073 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00007074 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007075
Denis Vlasenkof9375282009-04-05 19:13:39 +00007076 /* Block some signals */
7077 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007078
Mike Frysinger38478a62009-05-20 04:48:06 -04007079 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007080 /* Set other signals to restore saved_tty_pgrp */
7081 set_fatal_handlers();
7082 /* Put ourselves in our own process group
7083 * (bash, too, does this only if ctty is available) */
7084 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
7085 /* Grab control of the terminal */
7086 tcsetpgrp(G_interactive_fd, getpid());
7087 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00007088 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00007089 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00007090 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00007091 } else if (!signal_mask_is_inited) {
7092 block_signals(0); /* 0: called 1st time */
7093 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007094#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00007095 /* No job control compiled in, only prompt/line editing */
7096 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007097 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
7098 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007099 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007100 G_interactive_fd = dup(STDIN_FILENO);
7101 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007102 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007103 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00007104 }
7105 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007106 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007107 close_on_exec_on(G_interactive_fd);
7108 block_signals(signal_mask_is_inited);
7109 } else if (!signal_mask_is_inited) {
7110 block_signals(0);
7111 }
7112#else
7113 /* We have interactiveness code disabled */
7114 if (!signal_mask_is_inited) {
7115 block_signals(0);
7116 }
7117#endif
7118 /* bash:
7119 * if interactive but not a login shell, sources ~/.bashrc
7120 * (--norc turns this off, --rcfile <file> overrides)
7121 */
7122
7123 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007124 /* note: ash and hush share this string */
7125 printf("\n\n%s %s\n"
7126 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7127 "\n",
7128 bb_banner,
7129 "hush - the humble shell"
7130 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007131 }
7132
Denis Vlasenkof9375282009-04-05 19:13:39 +00007133 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007134
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007135 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007136#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007137 if (G.cwd != bb_msg_unknown)
7138 free((char*)G.cwd);
7139 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007140 while (cur_var) {
7141 struct variable *tmp = cur_var;
7142 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007143 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007144 cur_var = cur_var->next;
7145 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007146 }
Eric Andersen25f27032001-04-26 23:22:31 +00007147#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007148 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007149}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007150
7151
7152#if ENABLE_LASH
7153int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7154int lash_main(int argc, char **argv)
7155{
Denys Vlasenko07934912009-08-20 03:40:04 +02007156 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007157 return hush_main(argc, argv);
7158}
7159#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007160
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007161#if ENABLE_MSH
7162int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7163int msh_main(int argc, char **argv)
7164{
7165 //bb_error_msg("msh is deprecated, please use hush instead");
7166 return hush_main(argc, argv);
7167}
7168#endif
7169
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007170
7171/*
7172 * Built-ins
7173 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007174static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007175{
7176 return 0;
7177}
7178
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007179static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007180{
7181 int argc = 0;
7182 while (*argv) {
7183 argc++;
7184 argv++;
7185 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007186 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007187}
7188
7189static int FAST_FUNC builtin_test(char **argv)
7190{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007191 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007192}
7193
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007194static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007195{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007196 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007197}
7198
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007199#if ENABLE_PRINTF
7200static int FAST_FUNC builtin_printf(char **argv)
7201{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007202 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007203}
7204#endif
7205
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007206static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007207{
7208 int rcode = EXIT_SUCCESS;
7209
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007210 if (*++argv) {
7211 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007212 /* bash:
7213 * eval "echo Hi; done" ("done" is syntax error):
7214 * "echo Hi" will not execute too.
7215 */
7216 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007217 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007218 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007219 }
7220 return rcode;
7221}
7222
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007223static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007224{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007225 const char *newdir = argv[1];
7226 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007227 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007228 * bash says "bash: cd: HOME not set" and does nothing
7229 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007230 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007231 const char *home = get_local_var_value("HOME");
7232 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007233 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007234 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007235 /* Mimic bash message exactly */
7236 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007237 return EXIT_FAILURE;
7238 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007239 /* Read current dir (get_cwd(1) is inside) and set PWD.
7240 * Note: do not enforce exporting. If PWD was unset or unexported,
7241 * set it again, but do not export. bash does the same.
7242 */
7243 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007244 return EXIT_SUCCESS;
7245}
7246
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007247static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007248{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007249 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007250 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007251
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007252 /* Careful: we can end up here after [v]fork. Do not restore
7253 * tty pgrp then, only top-level shell process does that */
7254 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7255 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7256
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007257 /* TODO: if exec fails, bash does NOT exit! We do.
7258 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7259 * and tcsetpgrp, and this is inherently racy.
7260 */
7261 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007262}
7263
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007264static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007265{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007266 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007267
7268 /* interactive bash:
7269 * # trap "echo EEE" EXIT
7270 * # exit
7271 * exit
7272 * There are stopped jobs.
7273 * (if there are _stopped_ jobs, running ones don't count)
7274 * # exit
7275 * exit
7276 # EEE (then bash exits)
7277 *
7278 * we can use G.exiting = -1 as indicator "last cmd was exit"
7279 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007280
7281 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007282 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007283 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007284 /* mimic bash: exit 123abc == exit 255 + error msg */
7285 xfunc_error_retval = 255;
7286 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007287 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007288}
7289
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007290static void print_escaped(const char *s)
7291{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007292 if (*s == '\'')
7293 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007294 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007295 const char *p = strchrnul(s, '\'');
7296 /* print 'xxxx', possibly just '' */
7297 printf("'%.*s'", (int)(p - s), s);
7298 if (*p == '\0')
7299 break;
7300 s = p;
7301 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007302 /* s points to '; print "'''...'''" */
7303 putchar('"');
7304 do putchar('\''); while (*++s == '\'');
7305 putchar('"');
7306 } while (*s);
7307}
7308
Denys Vlasenko295fef82009-06-03 12:47:26 +02007309#if !ENABLE_HUSH_LOCAL
7310#define helper_export_local(argv, exp, lvl) \
7311 helper_export_local(argv, exp)
7312#endif
7313static void helper_export_local(char **argv, int exp, int lvl)
7314{
7315 do {
7316 char *name = *argv;
7317
7318 /* So far we do not check that name is valid (TODO?) */
7319
7320 if (strchr(name, '=') == NULL) {
7321 struct variable *var;
7322
7323 var = get_local_var(name);
7324 if (exp == -1) { /* unexporting? */
7325 /* export -n NAME (without =VALUE) */
7326 if (var) {
7327 var->flg_export = 0;
7328 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7329 unsetenv(name);
7330 } /* else: export -n NOT_EXISTING_VAR: no-op */
7331 continue;
7332 }
7333 if (exp == 1) { /* exporting? */
7334 /* export NAME (without =VALUE) */
7335 if (var) {
7336 var->flg_export = 1;
7337 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7338 putenv(var->varstr);
7339 continue;
7340 }
7341 }
7342 /* Exporting non-existing variable.
7343 * bash does not put it in environment,
7344 * but remembers that it is exported,
7345 * and does put it in env when it is set later.
7346 * We just set it to "" and export. */
7347 /* Or, it's "local NAME" (without =VALUE).
7348 * bash sets the value to "". */
7349 name = xasprintf("%s=", name);
7350 } else {
7351 /* (Un)exporting/making local NAME=VALUE */
7352 name = xstrdup(name);
7353 }
7354 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7355 } while (*++argv);
7356}
7357
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007358static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007359{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007360 unsigned opt_unexport;
7361
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007362#if ENABLE_HUSH_EXPORT_N
7363 /* "!": do not abort on errors */
7364 opt_unexport = getopt32(argv, "!n");
7365 if (opt_unexport == (uint32_t)-1)
7366 return EXIT_FAILURE;
7367 argv += optind;
7368#else
7369 opt_unexport = 0;
7370 argv++;
7371#endif
7372
7373 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007374 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007375 if (e) {
7376 while (*e) {
7377#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007378 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007379#else
7380 /* ash emits: export VAR='VAL'
7381 * bash: declare -x VAR="VAL"
7382 * we follow ash example */
7383 const char *s = *e++;
7384 const char *p = strchr(s, '=');
7385
7386 if (!p) /* wtf? take next variable */
7387 continue;
7388 /* export var= */
7389 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007390 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007391 putchar('\n');
7392#endif
7393 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007394 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007395 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007396 return EXIT_SUCCESS;
7397 }
7398
Denys Vlasenko295fef82009-06-03 12:47:26 +02007399 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007400
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007401 return EXIT_SUCCESS;
7402}
7403
Denys Vlasenko295fef82009-06-03 12:47:26 +02007404#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007405static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007406{
7407 if (G.func_nest_level == 0) {
7408 bb_error_msg("%s: not in a function", argv[0]);
7409 return EXIT_FAILURE; /* bash compat */
7410 }
7411 helper_export_local(argv, 0, G.func_nest_level);
7412 return EXIT_SUCCESS;
7413}
7414#endif
7415
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007416static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007417{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007418 int sig;
7419 char *new_cmd;
7420
7421 if (!G.traps)
7422 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7423
7424 argv++;
7425 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007426 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007427 /* No args: print all trapped */
7428 for (i = 0; i < NSIG; ++i) {
7429 if (G.traps[i]) {
7430 printf("trap -- ");
7431 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007432 /* note: bash adds "SIG", but only if invoked
7433 * as "bash". If called as "sh", or if set -o posix,
7434 * then it prints short signal names.
7435 * We are printing short names: */
7436 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007437 }
7438 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007439 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007440 return EXIT_SUCCESS;
7441 }
7442
7443 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007444 /* If first arg is a number: reset all specified signals */
7445 sig = bb_strtou(*argv, NULL, 10);
7446 if (errno == 0) {
7447 int ret;
7448 process_sig_list:
7449 ret = EXIT_SUCCESS;
7450 while (*argv) {
7451 sig = get_signum(*argv++);
7452 if (sig < 0 || sig >= NSIG) {
7453 ret = EXIT_FAILURE;
7454 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007455 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007456 continue;
7457 }
7458
7459 free(G.traps[sig]);
7460 G.traps[sig] = xstrdup(new_cmd);
7461
7462 debug_printf("trap: setting SIG%s (%i) to '%s'",
7463 get_signame(sig), sig, G.traps[sig]);
7464
7465 /* There is no signal for 0 (EXIT) */
7466 if (sig == 0)
7467 continue;
7468
7469 if (new_cmd) {
7470 sigaddset(&G.blocked_set, sig);
7471 } else {
7472 /* There was a trap handler, we are removing it
7473 * (if sig has non-DFL handling,
7474 * we don't need to do anything) */
7475 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7476 continue;
7477 sigdelset(&G.blocked_set, sig);
7478 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007479 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007480 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007481 return ret;
7482 }
7483
7484 if (!argv[1]) { /* no second arg */
7485 bb_error_msg("trap: invalid arguments");
7486 return EXIT_FAILURE;
7487 }
7488
7489 /* First arg is "-": reset all specified to default */
7490 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7491 /* Everything else: set arg as signal handler
7492 * (includes "" case, which ignores signal) */
7493 if (argv[0][0] == '-') {
7494 if (argv[0][1] == '\0') { /* "-" */
7495 /* new_cmd remains NULL: "reset these sigs" */
7496 goto reset_traps;
7497 }
7498 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7499 argv++;
7500 }
7501 /* else: "-something", no special meaning */
7502 }
7503 new_cmd = *argv;
7504 reset_traps:
7505 argv++;
7506 goto process_sig_list;
7507}
7508
Mike Frysinger93cadc22009-05-27 17:06:25 -04007509/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007510static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007511{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007512 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007513
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007514 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007515 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007516 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007517
7518 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007519 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007520 type = "an alias";*/
7521#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007522 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007523 type = "a function";
7524#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007525 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007526 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007527 else if ((path = find_in_path(*argv)) != NULL)
7528 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007529 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007530 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007531 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007532 continue;
7533 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007534
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007535 printf("%s is %s\n", *argv, type);
7536 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007537 }
7538
7539 return ret;
7540}
7541
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007542#if ENABLE_HUSH_JOB
7543/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007544static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007545{
7546 int i, jobnum;
7547 struct pipe *pi;
7548
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007549 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007550 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007551
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007552 /* If they gave us no args, assume they want the last backgrounded task */
7553 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007554 for (pi = G.job_list; pi; pi = pi->next) {
7555 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007556 goto found;
7557 }
7558 }
7559 bb_error_msg("%s: no current job", argv[0]);
7560 return EXIT_FAILURE;
7561 }
7562 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7563 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7564 return EXIT_FAILURE;
7565 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007566 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007567 if (pi->jobid == jobnum) {
7568 goto found;
7569 }
7570 }
7571 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7572 return EXIT_FAILURE;
7573 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007574 /* TODO: bash prints a string representation
7575 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007576 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007577 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007578 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007579 }
7580
7581 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007582 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7583 for (i = 0; i < pi->num_cmds; i++) {
7584 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7585 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007586 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007587 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007588
7589 i = kill(- pi->pgrp, SIGCONT);
7590 if (i < 0) {
7591 if (errno == ESRCH) {
7592 delete_finished_bg_job(pi);
7593 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007594 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007595 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007596 }
7597
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007598 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007599 remove_bg_job(pi);
7600 return checkjobs_and_fg_shell(pi);
7601 }
7602 return EXIT_SUCCESS;
7603}
7604#endif
7605
7606#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007607static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007608{
7609 const struct built_in_command *x;
7610
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007611 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007612 "Built-in commands:\n"
7613 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007614 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7615 if (x->descr)
7616 printf("%s\t%s\n", x->cmd, x->descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007617 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007618 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007619 return EXIT_SUCCESS;
7620}
7621#endif
7622
7623#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007624static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007625{
7626 struct pipe *job;
7627 const char *status_string;
7628
Denis Vlasenko87a86552008-07-29 19:43:10 +00007629 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007630 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007631 status_string = "Stopped";
7632 else
7633 status_string = "Running";
7634
7635 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7636 }
7637 return EXIT_SUCCESS;
7638}
7639#endif
7640
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007641#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007642static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007643{
7644 void *p;
7645 unsigned long l;
7646
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007647# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007648 /* Optional. Reduces probability of false positives */
7649 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007650# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007651 /* Crude attempt to find where "free memory" starts,
7652 * sans fragmentation. */
7653 p = malloc(240);
7654 l = (unsigned long)p;
7655 free(p);
7656 p = malloc(3400);
7657 if (l < (unsigned long)p) l = (unsigned long)p;
7658 free(p);
7659
7660 if (!G.memleak_value)
7661 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007662
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007663 l -= G.memleak_value;
7664 if ((long)l < 0)
7665 l = 0;
7666 l /= 1024;
7667 if (l > 127)
7668 l = 127;
7669
7670 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7671 return l;
7672}
7673#endif
7674
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007675static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007676{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007677 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007678 return EXIT_SUCCESS;
7679}
7680
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007681static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007682{
7683 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007684 const char *name = "REPLY";
7685
7686 if (argv[1]) {
7687 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007688 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7689 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007690 if (!is_well_formed_var_name(name, '\0')) {
7691 /* Mimic bash message */
7692 bb_error_msg("read: '%s': not a valid identifier", name);
7693 return 1;
7694 }
7695 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007696
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007697//TODO: bash unbackslashes input, splits words and puts them in argv[i]
7698
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007699 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denys Vlasenko295fef82009-06-03 12:47:26 +02007700 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007701}
7702
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007703/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7704 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007705 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007706 * set [-abCefhmnuvx] [-o option] [argument...]
7707 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007708 * set -- [argument...]
7709 * set -o
7710 * set +o
7711 * Implementations shall support the options in both their hyphen and
7712 * plus-sign forms. These options can also be specified as options to sh.
7713 * Examples:
7714 * Write out all variables and their values: set
7715 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7716 * Turn on the -x and -v options: set -xv
7717 * Unset all positional parameters: set --
7718 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7719 * Set the positional parameters to the expansion of x, even if x expands
7720 * with a leading '-' or '+': set -- $x
7721 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007722 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007723 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007724static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007725{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007726 int n;
7727 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007728 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007729
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007730 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007731 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007732 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007733 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007734 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007735 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007736
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007737 do {
7738 if (!strcmp(arg, "--")) {
7739 ++argv;
7740 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007741 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007742 if (arg[0] != '+' && arg[0] != '-')
7743 break;
7744 for (n = 1; arg[n]; ++n)
7745 if (set_mode(arg[0], arg[n]))
7746 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007747 } while ((arg = *++argv) != NULL);
7748 /* Now argv[0] is 1st argument */
7749
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007750 if (arg == NULL)
7751 return EXIT_SUCCESS;
7752 set_argv:
7753
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007754 /* NB: G.global_argv[0] ($0) is never freed/changed */
7755 g_argv = G.global_argv;
7756 if (G.global_args_malloced) {
7757 pp = g_argv;
7758 while (*++pp)
7759 free(*pp);
7760 g_argv[1] = NULL;
7761 } else {
7762 G.global_args_malloced = 1;
7763 pp = xzalloc(sizeof(pp[0]) * 2);
7764 pp[0] = g_argv[0]; /* retain $0 */
7765 g_argv = pp;
7766 }
7767 /* This realloc's G.global_argv */
7768 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7769
7770 n = 1;
7771 while (*++pp)
7772 n++;
7773 G.global_argc = n;
7774
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007775 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007776
7777 /* Nothing known, so abort */
7778 error:
7779 bb_error_msg("set: %s: invalid option", arg);
7780 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007781}
7782
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007783static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007784{
7785 int n = 1;
7786 if (argv[1]) {
7787 n = atoi(argv[1]);
7788 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007789 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007790 if (G.global_args_malloced) {
7791 int m = 1;
7792 while (m <= n)
7793 free(G.global_argv[m++]);
7794 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007795 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007796 memmove(&G.global_argv[1], &G.global_argv[n+1],
7797 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007798 return EXIT_SUCCESS;
7799 }
7800 return EXIT_FAILURE;
7801}
7802
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007803static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007804{
Mike Frysinger93cadc22009-05-27 17:06:25 -04007805 char *arg_path;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007806 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007807 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007808#if ENABLE_HUSH_FUNCTIONS
7809 smallint sv_flg;
7810#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007811
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007812 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007813 return EXIT_FAILURE;
7814
Mike Frysinger93cadc22009-05-27 17:06:25 -04007815 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7816 input = fopen_for_read(arg_path);
7817 free(arg_path);
7818 } else
7819 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007820 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007821 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007822 return EXIT_FAILURE;
7823 }
7824 close_on_exec_on(fileno(input));
7825
Mike Frysinger885b6f22009-04-18 21:04:25 +00007826#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007827 sv_flg = G.flag_return_in_progress;
7828 /* "we are inside sourced file, ok to use return" */
7829 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007830#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007831 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007832
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007833 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007834 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007835
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007836 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007837#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007838 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007839#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007840
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007841 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007842}
7843
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007844static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007845{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007846 int rc;
7847 mode_t mask;
7848
7849 mask = umask(0);
7850 if (argv[1]) {
7851 mode_t old_mask = mask;
7852
7853 mask ^= 0777;
7854 rc = bb_parse_mode(argv[1], &mask);
7855 mask ^= 0777;
7856 if (rc == 0) {
7857 mask = old_mask;
7858 /* bash messages:
7859 * bash: umask: 'q': invalid symbolic mode operator
7860 * bash: umask: 999: octal number out of range
7861 */
7862 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007863 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007864 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007865 rc = 1;
7866 /* Mimic bash */
7867 printf("%04o\n", (unsigned) mask);
7868 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007869 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007870 umask(mask);
7871
7872 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007873}
7874
Mike Frysingerd690f682009-03-30 06:50:54 +00007875/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007876static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007877{
Mike Frysingerd690f682009-03-30 06:50:54 +00007878 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007879 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007880
Denis Vlasenko28e67962009-04-26 23:22:40 +00007881 /* "!": do not abort on errors */
7882 /* "+": stop at 1st non-option */
7883 opts = getopt32(argv, "!+vf");
7884 if (opts == (unsigned)-1)
7885 return EXIT_FAILURE;
7886 if (opts == 3) {
7887 bb_error_msg("unset: -v and -f are exclusive");
7888 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007889 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007890 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007891
7892 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007893 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007894 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007895 if (unset_local_var(*argv)) {
7896 /* unset <nonexistent_var> doesn't fail.
7897 * Error is when one tries to unset RO var.
7898 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007899 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007900 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007901 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007902#if ENABLE_HUSH_FUNCTIONS
7903 else {
7904 unset_func(*argv);
7905 }
7906#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007907 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007908 }
7909 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007910}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007911
Mike Frysinger56bdea12009-03-28 20:01:58 +00007912/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007913static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00007914{
7915 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007916 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007917
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007918 if (*++argv == NULL) {
7919 /* Don't care about wait results */
7920 /* Note 1: must wait until there are no more children */
7921 /* Note 2: must be interruptible */
7922 /* Examples:
7923 * $ sleep 3 & sleep 6 & wait
7924 * [1] 30934 sleep 3
7925 * [2] 30935 sleep 6
7926 * [1] Done sleep 3
7927 * [2] Done sleep 6
7928 * $ sleep 3 & sleep 6 & wait
7929 * [1] 30936 sleep 3
7930 * [2] 30937 sleep 6
7931 * [1] Done sleep 3
7932 * ^C <-- after ~4 sec from keyboard
7933 * $
7934 */
7935 sigaddset(&G.blocked_set, SIGCHLD);
7936 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7937 while (1) {
7938 checkjobs(NULL);
7939 if (errno == ECHILD)
7940 break;
7941 /* Wait for SIGCHLD or any other signal of interest */
7942 /* sigtimedwait with infinite timeout: */
7943 sig = sigwaitinfo(&G.blocked_set, NULL);
7944 if (sig > 0) {
7945 sig = check_and_run_traps(sig);
7946 if (sig && sig != SIGCHLD) { /* see note 2 */
7947 ret = 128 + sig;
7948 break;
7949 }
7950 }
7951 }
7952 sigdelset(&G.blocked_set, SIGCHLD);
7953 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7954 return ret;
7955 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007956
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007957 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007958 while (*argv) {
7959 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007960 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007961 /* mimic bash message */
7962 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007963 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007964 }
7965 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007966 if (WIFSIGNALED(status))
7967 ret = 128 + WTERMSIG(status);
7968 else if (WIFEXITED(status))
7969 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007970 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007971 ret = EXIT_FAILURE;
7972 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007973 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007974 ret = 127;
7975 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007976 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007977 }
7978
7979 return ret;
7980}
7981
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007982#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7983static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7984{
7985 if (argv[1]) {
7986 def = bb_strtou(argv[1], NULL, 10);
7987 if (errno || def < def_min || argv[2]) {
7988 bb_error_msg("%s: bad arguments", argv[0]);
7989 def = UINT_MAX;
7990 }
7991 }
7992 return def;
7993}
7994#endif
7995
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007996#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007997static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007998{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007999 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00008000 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008001 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00008002 return EXIT_SUCCESS; /* bash compat */
8003 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00008004 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008005
8006 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
8007 if (depth == UINT_MAX)
8008 G.flag_break_continue = BC_BREAK;
8009 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00008010 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008011
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008012 return EXIT_SUCCESS;
8013}
8014
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008015static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008016{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00008017 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
8018 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00008019}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00008020#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008021
8022#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008023static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00008024{
8025 int rc;
8026
8027 if (G.flag_return_in_progress != -1) {
8028 bb_error_msg("%s: not in a function or sourced script", argv[0]);
8029 return EXIT_FAILURE; /* bash compat */
8030 }
8031
8032 G.flag_return_in_progress = 1;
8033
8034 /* bash:
8035 * out of range: wraps around at 256, does not error out
8036 * non-numeric param:
8037 * f() { false; return qwe; }; f; echo $?
8038 * bash: return: qwe: numeric argument required <== we do this
8039 * 255 <== we also do this
8040 */
8041 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
8042 return rc;
8043}
8044#endif