blob: 171b7394026eb712ad4e53441416448bb8cd570f [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 Vlasenkob61e13d2008-06-17 05:11:43 +0000892static int glob_needed(const char *s)
893{
894 while (*s) {
895 if (*s == '\\')
896 s++;
897 if (*s == '*' || *s == '[' || *s == '?')
898 return 1;
899 s++;
900 }
901 return 0;
902}
903
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000904static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000905{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000906 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000907 return 0;
908 s++;
909 while (isalnum(*s) || *s == '_')
910 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000911 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000912}
913
Denis Vlasenko55789c62008-06-18 16:30:42 +0000914/* Replace each \x with x in place, return ptr past NUL. */
915static char *unbackslash(char *src)
916{
Denys Vlasenko71885402009-09-24 01:44:13 +0200917 char *dst = src = strchrnul(src, '\\');
Denis Vlasenko55789c62008-06-18 16:30:42 +0000918 while (1) {
919 if (*src == '\\')
920 src++;
921 if ((*dst++ = *src++) == '\0')
922 break;
923 }
924 return dst;
925}
926
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000927static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000928{
929 int i;
930 unsigned count1;
931 unsigned count2;
932 char **v;
933
934 v = strings;
935 count1 = 0;
936 if (v) {
937 while (*v) {
938 count1++;
939 v++;
940 }
941 }
942 count2 = 0;
943 v = add;
944 while (*v) {
945 count2++;
946 v++;
947 }
948 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
949 v[count1 + count2] = NULL;
950 i = count2;
951 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000952 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000953 return v;
954}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000955#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000956static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
957{
958 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
959 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
960 return ptr;
961}
962#define add_strings_to_strings(strings, add, need_to_dup) \
963 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
964#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000965
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200966/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000967static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000968{
969 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000970 v[0] = add;
971 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000972 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000973}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000974#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000975static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
976{
977 char **ptr = add_string_to_strings(strings, add);
978 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
979 return ptr;
980}
981#define add_string_to_strings(strings, add) \
982 xx_add_string_to_strings(__LINE__, strings, add)
983#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000984
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200985static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000986{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000987 char **v;
988
989 if (!strings)
990 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000991 v = strings;
992 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200993 free(*v);
994 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000995 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000996 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000997}
998
Denis Vlasenko76d50412008-06-10 16:19:39 +0000999
Denis Vlasenko270b1c32009-04-17 18:54:50 +00001000/* Helpers for setting new $n and restoring them back
1001 */
1002typedef struct save_arg_t {
1003 char *sv_argv0;
1004 char **sv_g_argv;
1005 int sv_g_argc;
1006 smallint sv_g_malloced;
1007} save_arg_t;
1008
1009static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1010{
1011 int n;
1012
1013 sv->sv_argv0 = argv[0];
1014 sv->sv_g_argv = G.global_argv;
1015 sv->sv_g_argc = G.global_argc;
1016 sv->sv_g_malloced = G.global_args_malloced;
1017
1018 argv[0] = G.global_argv[0]; /* retain $0 */
1019 G.global_argv = argv;
1020 G.global_args_malloced = 0;
1021
1022 n = 1;
1023 while (*++argv)
1024 n++;
1025 G.global_argc = n;
1026}
1027
1028static void restore_G_args(save_arg_t *sv, char **argv)
1029{
1030 char **pp;
1031
1032 if (G.global_args_malloced) {
1033 /* someone ran "set -- arg1 arg2 ...", undo */
1034 pp = G.global_argv;
1035 while (*++pp) /* note: does not free $0 */
1036 free(*pp);
1037 free(G.global_argv);
1038 }
1039 argv[0] = sv->sv_argv0;
1040 G.global_argv = sv->sv_g_argv;
1041 G.global_argc = sv->sv_g_argc;
1042 G.global_args_malloced = sv->sv_g_malloced;
1043}
1044
1045
Denis Vlasenkod5762932009-03-31 11:22:57 +00001046/* Basic theory of signal handling in shell
1047 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001048 * This does not describe what hush does, rather, it is current understanding
1049 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001050 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1051 *
1052 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1053 * is finished or backgrounded. It is the same in interactive and
1054 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001055 * a user trap handler is installed or a shell special one is in effect.
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001056 * ^C or ^Z from keyboard seems to execute "at once" because it usually
Denis Vlasenkod5762932009-03-31 11:22:57 +00001057 * backgrounds (i.e. stops) or kills all members of currently running
1058 * pipe.
1059 *
1060 * Wait builtin in interruptible by signals for which user trap is set
1061 * or by SIGINT in interactive shell.
1062 *
1063 * Trap handlers will execute even within trap handlers. (right?)
1064 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001065 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001066 *
1067 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001068 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001069 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001070 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001071 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001072 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001073 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001074 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001075 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001076 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001077 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001078 *
1079 * SIGQUIT: ignore
1080 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001081 * SIGHUP (interactive):
1082 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001083 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001084 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1085 * that all pipe members are stopped. Try this in bash:
1086 * while :; do :; done - ^Z does not background it
1087 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001088 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001089 * of the command line, show prompt. NB: ^C does not send SIGINT
1090 * to interactive shell while shell is waiting for a pipe,
1091 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001092 * Example 1: this waits 5 sec, but does not execute ls:
1093 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1094 * Example 2: this does not wait and does not execute ls:
1095 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1096 * Example 3: this does not wait 5 sec, but executes ls:
1097 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001098 *
1099 * (What happens to signals which are IGN on shell start?)
1100 * (What happens with signal mask on shell start?)
1101 *
1102 * Implementation in hush
1103 * ======================
1104 * We use in-kernel pending signal mask to determine which signals were sent.
1105 * We block all signals which we don't want to take action immediately,
1106 * i.e. we block all signals which need to have special handling as described
1107 * above, and all signals which have traps set.
1108 * After each pipe execution, we extract any pending signals via sigtimedwait()
1109 * and act on them.
1110 *
1111 * unsigned non_DFL_mask: a mask of such "special" signals
1112 * sigset_t blocked_set: current blocked signal set
1113 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001114 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001115 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001116 * "trap 'cmd' SIGxxx":
1117 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001118 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001119 * unblock signals with special interactive handling
1120 * (child shell is not interactive),
1121 * unset all traps (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001122 * after [v]fork, if we plan to exec:
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02001123 * POSIX says fork clears pending signal mask in child - no need to clear it.
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001124 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001125 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001126 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001127 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001128 * and to restore tty pgrp on signal-induced exit.
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001129 *
Denys Vlasenko67f71862009-09-25 14:21:06 +02001130 * Note 2 (compat):
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02001131 * Standard says "When a subshell is entered, traps that are not being ignored
1132 * are set to the default actions". bash interprets it so that traps which
Denys Vlasenko67f71862009-09-25 14:21:06 +02001133 * are set to "" (ignore) are NOT reset to defaults. We do the same.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001134 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001135enum {
1136 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001137 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001138 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001139 | (1 << SIGHUP)
1140 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001141 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001142#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001143 | (1 << SIGTTIN)
1144 | (1 << SIGTTOU)
1145 | (1 << SIGTSTP)
1146#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001147};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001148
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001149#if ENABLE_HUSH_FAST
1150static void SIGCHLD_handler(int sig UNUSED_PARAM)
1151{
1152 G.count_SIGCHLD++;
1153//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1154}
1155#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001156
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001157#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001158
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001159/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1160#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001161/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001162#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1163
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001164/* Restores tty foreground process group, and exits.
1165 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001166 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001167 * or called directly with -EXITCODE.
1168 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001169static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001170static void sigexit(int sig)
1171{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001172 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001173 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001174
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001175 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001176 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001177 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1178 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001179
1180 /* Not a signal, just exit */
1181 if (sig <= 0)
1182 _exit(- sig);
1183
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001184 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001185}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001186#else
1187
1188#define disable_restore_tty_pgrp_on_exit() ((void)0)
1189#define enable_restore_tty_pgrp_on_exit() ((void)0)
1190
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001191#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001192
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001193/* Restores tty foreground process group, and exits. */
1194static void hush_exit(int exitcode) NORETURN;
1195static void hush_exit(int exitcode)
1196{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001197 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1198 /* Prevent recursion:
1199 * trap "echo Hi; exit" EXIT; exit
1200 */
1201 char *argv[] = { NULL, G.traps[0], NULL };
1202 G.traps[0] = NULL;
1203 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001204 builtin_eval(argv);
1205 free(argv[1]);
1206 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001207
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001208#if ENABLE_HUSH_JOB
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001209 fflush_all();
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001210 sigexit(- (exitcode & 0xff));
1211#else
1212 exit(exitcode);
1213#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001214}
1215
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001216static int check_and_run_traps(int sig)
1217{
1218 static const struct timespec zero_timespec = { 0, 0 };
1219 smalluint save_rcode;
1220 int last_sig = 0;
1221
1222 if (sig)
1223 goto jump_in;
1224 while (1) {
1225 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1226 if (sig <= 0)
1227 break;
1228 jump_in:
1229 last_sig = sig;
1230 if (G.traps && G.traps[sig]) {
1231 if (G.traps[sig][0]) {
1232 /* We have user-defined handler */
1233 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1234 save_rcode = G.last_exitcode;
1235 builtin_eval(argv);
1236 free(argv[1]);
1237 G.last_exitcode = save_rcode;
1238 } /* else: "" trap, ignoring signal */
1239 continue;
1240 }
1241 /* not a trap: special action */
1242 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001243#if ENABLE_HUSH_FAST
1244 case SIGCHLD:
1245 G.count_SIGCHLD++;
1246//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1247 break;
1248#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001249 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001250 /* Builtin was ^C'ed, make it look prettier: */
1251 bb_putchar('\n');
1252 G.flag_SIGINT = 1;
1253 break;
1254#if ENABLE_HUSH_JOB
1255 case SIGHUP: {
1256 struct pipe *job;
1257 /* bash is observed to signal whole process groups,
1258 * not individual processes */
1259 for (job = G.job_list; job; job = job->next) {
1260 if (job->pgrp <= 0)
1261 continue;
1262 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1263 if (kill(- job->pgrp, SIGHUP) == 0)
1264 kill(- job->pgrp, SIGCONT);
1265 }
1266 sigexit(SIGHUP);
1267 }
1268#endif
1269 default: /* ignored: */
1270 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1271 break;
1272 }
1273 }
1274 return last_sig;
1275}
1276
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001277
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001278static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001279{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001280 if (force || G.cwd == NULL) {
1281 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1282 * we must not try to free(bb_msg_unknown) */
1283 if (G.cwd == bb_msg_unknown)
1284 G.cwd = NULL;
1285 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1286 if (!G.cwd)
1287 G.cwd = bb_msg_unknown;
1288 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001289 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001290}
1291
Denis Vlasenko83506862007-11-23 13:11:42 +00001292
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001293/*
1294 * Shell and environment variable support
1295 */
1296static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001297{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001298 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001299 struct variable *cur;
1300 int len;
1301
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001302 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001303 pp = &G.top_var;
1304 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001305 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001306 return pp;
1307 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001308 }
1309 return NULL;
1310}
1311
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001312static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001313{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001314 struct variable **pp = get_ptr_to_local_var(name);
1315 if (pp)
1316 return *pp;
1317 return NULL;
1318}
1319
1320static const char *get_local_var_value(const char *name)
1321{
1322 struct variable **pp = get_ptr_to_local_var(name);
1323 if (pp)
1324 return strchr((*pp)->varstr, '=') + 1;
Denys Vlasenkodea47882009-10-09 15:40:49 +02001325 if (strcmp(name, "PPID") == 0)
1326 return utoa(G.root_ppid);
1327 // bash compat: UID? EUID?
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001328#if ENABLE_HUSH_RANDOM_SUPPORT
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001329 if (strcmp(name, "RANDOM") == 0) {
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001330 return utoa(next_random(&G.random_gen));
Denys Vlasenko8c66a9d2009-10-11 02:15:49 +02001331 }
Denys Vlasenko20b3d142009-10-09 20:59:39 +02001332#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001333 return NULL;
1334}
1335
1336/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001337 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001338 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001339 * 0: do not change export flag
1340 * (if creating new variable, flag will be 0)
1341 * 1: set export flag and putenv the variable
1342 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001343 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001344 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001345#if !BB_MMU && ENABLE_HUSH_LOCAL
1346/* all params are used */
1347#elif BB_MMU && ENABLE_HUSH_LOCAL
1348#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1349 set_local_var(str, flg_export, local_lvl)
1350#elif BB_MMU && !ENABLE_HUSH_LOCAL
1351#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001352 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001353#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1354#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1355 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001356#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001357static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001358{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001359 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001360 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001361 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001362 int name_len;
1363
Denis Vlasenko950bd722009-04-21 11:23:56 +00001364 eq_sign = strchr(str, '=');
1365 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001366 free(str);
1367 return -1;
1368 }
1369
Denis Vlasenko950bd722009-04-21 11:23:56 +00001370 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001371 var_pp = &G.top_var;
1372 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001373 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001374 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001375 continue;
1376 }
1377 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001378 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001379#if !BB_MMU
1380 if (!flg_read_only)
1381#endif
1382 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001383 free(str);
1384 return -1;
1385 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001386 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001387 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1388 *eq_sign = '\0';
1389 unsetenv(str);
1390 *eq_sign = '=';
1391 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001392#if ENABLE_HUSH_LOCAL
1393 if (cur->func_nest_level < local_lvl) {
1394 /* New variable is declared as local,
1395 * and existing one is global, or local
1396 * from enclosing function.
1397 * Remove and save old one: */
1398 *var_pp = cur->next;
1399 cur->next = *G.shadowed_vars_pp;
1400 *G.shadowed_vars_pp = cur;
1401 /* bash 3.2.33(1) and exported vars:
1402 * # export z=z
1403 * # f() { local z=a; env | grep ^z; }
1404 * # f
1405 * z=a
1406 * # env | grep ^z
1407 * z=z
1408 */
1409 if (cur->flg_export)
1410 flg_export = 1;
1411 break;
1412 }
1413#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001414 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001415 free_and_exp:
1416 free(str);
1417 goto exp;
1418 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001419 if (cur->max_len != 0) {
1420 if (cur->max_len >= strlen(str)) {
1421 /* This one is from startup env, reuse space */
1422 strcpy(cur->varstr, str);
1423 goto free_and_exp;
1424 }
1425 } else {
1426 /* max_len == 0 signifies "malloced" var, which we can
1427 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001428 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001429 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001430 cur->max_len = 0;
1431 goto set_str_and_exp;
1432 }
1433
Denys Vlasenko295fef82009-06-03 12:47:26 +02001434 /* Not found - create new variable struct */
1435 cur = xzalloc(sizeof(*cur));
1436#if ENABLE_HUSH_LOCAL
1437 cur->func_nest_level = local_lvl;
1438#endif
1439 cur->next = *var_pp;
1440 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001441
1442 set_str_and_exp:
1443 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001444#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001445 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001446#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001447 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001448 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001449 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001450 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1451 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001452 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001453 if (flg_export == -1) {
1454 cur->flg_export = 0;
1455 /* unsetenv was already done */
1456 } else {
1457 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1458 return putenv(cur->varstr);
1459 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001460 }
1461 return 0;
1462}
1463
Denys Vlasenko6db47842009-09-05 20:15:17 +02001464/* Used at startup and after each cd */
1465static void set_pwd_var(int exp)
1466{
1467 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1468 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1469}
1470
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001471static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001472{
1473 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001474 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001475
1476 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001477 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001478 var_pp = &G.top_var;
1479 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001480 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1481 if (cur->flg_read_only) {
1482 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001483 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001484 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001485 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001486 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1487 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001488 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1489 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001490 if (!cur->max_len)
1491 free(cur->varstr);
1492 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001493 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001494 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001495 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001496 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001497 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001498}
1499
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001500static int unset_local_var(const char *name)
1501{
1502 return unset_local_var_len(name, strlen(name));
1503}
1504
1505static void unset_vars(char **strings)
1506{
1507 char **v;
1508
1509 if (!strings)
1510 return;
1511 v = strings;
1512 while (*v) {
1513 const char *eq = strchrnul(*v, '=');
1514 unset_local_var_len(*v, (int)(eq - *v));
1515 v++;
1516 }
1517 free(strings);
1518}
1519
Mike Frysinger98c52642009-04-02 10:02:37 +00001520#if ENABLE_SH_MATH_SUPPORT
1521#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1522#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1523static char *endofname(const char *name)
1524{
1525 char *p;
1526
1527 p = (char *) name;
1528 if (!is_name(*p))
1529 return p;
1530 while (*++p) {
1531 if (!is_in_name(*p))
1532 break;
1533 }
1534 return p;
1535}
1536
1537static void arith_set_local_var(const char *name, const char *val, int flags)
1538{
1539 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001540 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001541 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001542}
1543#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001544
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001545
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001546/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001547 * Helpers for "var1=val1 var2=val2 cmd" feature
1548 */
1549static void add_vars(struct variable *var)
1550{
1551 struct variable *next;
1552
1553 while (var) {
1554 next = var->next;
1555 var->next = G.top_var;
1556 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001557 if (var->flg_export) {
1558 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001559 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001560 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001561 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001562 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001563 var = next;
1564 }
1565}
1566
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001567static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001568{
1569 char **s;
1570 struct variable *old = NULL;
1571
1572 if (!strings)
1573 return old;
1574 s = strings;
1575 while (*s) {
1576 struct variable *var_p;
1577 struct variable **var_pp;
1578 char *eq;
1579
1580 eq = strchr(*s, '=');
1581 if (eq) {
1582 *eq = '\0';
1583 var_pp = get_ptr_to_local_var(*s);
1584 *eq = '=';
1585 if (var_pp) {
1586 /* Remove variable from global linked list */
1587 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001588 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001589 *var_pp = var_p->next;
1590 /* Add it to returned list */
1591 var_p->next = old;
1592 old = var_p;
1593 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001594 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001595 }
1596 s++;
1597 }
1598 return old;
1599}
1600
1601
1602/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001603 * in_str support
1604 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001605static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001606{
1607 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001608 if (ch != '\0')
1609 return ch;
1610 i->p--;
1611 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001612}
1613
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001614static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001615{
1616 return *i->p;
1617}
1618
1619#if ENABLE_HUSH_INTERACTIVE
1620
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001621static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001622{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001623 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001624 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001625 if (G.PS1 == NULL)
1626 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001627 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001628 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001629 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001630 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001631 if (G.PS2 == NULL)
1632 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001633}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001634
1635static const char* setup_prompt_string(int promptmode)
1636{
1637 const char *prompt_str;
1638 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001639 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1640 /* Set up the prompt */
1641 if (promptmode == 0) { /* PS1 */
1642 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001643 /* bash uses $PWD value, even if it is set by user.
1644 * It uses current dir only if PWD is unset.
1645 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001646 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001647 prompt_str = G.PS1;
1648 } else
1649 prompt_str = G.PS2;
1650 } else
1651 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001652 debug_printf("result '%s'\n", prompt_str);
1653 return prompt_str;
1654}
1655
1656static void get_user_input(struct in_str *i)
1657{
1658 int r;
1659 const char *prompt_str;
1660
1661 prompt_str = setup_prompt_string(i->promptmode);
1662#if ENABLE_FEATURE_EDITING
1663 /* Enable command line editing only while a command line
1664 * is actually being read */
1665 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001666 G.flag_SIGINT = 0;
1667 /* buglet: SIGINT will not make new prompt to appear _at once_,
1668 * only after <Enter>. (^C will work) */
Denys Vlasenkoaaa22d22009-10-19 16:34:39 +02001669 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 +00001670 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001671 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001672 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001673 i->eof_flag = (r < 0);
1674 if (i->eof_flag) { /* EOF/error detected */
1675 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1676 G.user_input_buf[1] = '\0';
1677 }
1678#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001679 do {
1680 G.flag_SIGINT = 0;
1681 fputs(prompt_str, stdout);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01001682 fflush_all();
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001683 G.user_input_buf[0] = r = fgetc(i->file);
1684 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001685//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001686 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001687 i->eof_flag = (r == EOF);
1688#endif
1689 i->p = G.user_input_buf;
1690}
1691
1692#endif /* INTERACTIVE */
1693
1694/* This is the magic location that prints prompts
1695 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001696static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001697{
1698 int ch;
1699
1700 /* If there is data waiting, eat it up */
1701 if (i->p && *i->p) {
1702#if ENABLE_HUSH_INTERACTIVE
1703 take_cached:
1704#endif
1705 ch = *i->p++;
1706 if (i->eof_flag && !*i->p)
1707 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001708 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001709 } else {
1710 /* need to double check i->file because we might be doing something
1711 * more complicated by now, like sourcing or substituting. */
1712#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001713 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001714 do {
1715 get_user_input(i);
1716 } while (!*i->p); /* need non-empty line */
1717 i->promptmode = 1; /* PS2 */
1718 i->promptme = 0;
1719 goto take_cached;
1720 }
1721#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001722 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001723 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001724 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001725#if ENABLE_HUSH_INTERACTIVE
1726 if (ch == '\n')
1727 i->promptme = 1;
1728#endif
1729 return ch;
1730}
1731
Denis Vlasenko913a2012009-04-05 22:17:04 +00001732/* All callers guarantee this routine will never
1733 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001734 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001735static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001736{
1737 int ch;
1738 if (i->p && *i->p) {
1739 if (i->eof_flag && !i->p[1])
1740 return EOF;
1741 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001742 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001743 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001744 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001745 i->eof_flag = (ch == EOF);
1746 i->peek_buf[0] = ch;
1747 i->peek_buf[1] = '\0';
1748 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001749 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001750 return ch;
1751}
1752
1753static void setup_file_in_str(struct in_str *i, FILE *f)
1754{
1755 i->peek = file_peek;
1756 i->get = file_get;
1757#if ENABLE_HUSH_INTERACTIVE
1758 i->promptme = 1;
1759 i->promptmode = 0; /* PS1 */
1760#endif
1761 i->file = f;
1762 i->p = NULL;
1763}
1764
1765static void setup_string_in_str(struct in_str *i, const char *s)
1766{
1767 i->peek = static_peek;
1768 i->get = static_get;
1769#if ENABLE_HUSH_INTERACTIVE
1770 i->promptme = 1;
1771 i->promptmode = 0; /* PS1 */
1772#endif
1773 i->p = s;
1774 i->eof_flag = 0;
1775}
1776
1777
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001778/*
1779 * o_string support
1780 */
1781#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001782
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001783static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001784{
1785 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001786 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001787 if (o->data)
1788 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001789}
1790
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001791static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001792{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001793 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001794 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001795}
1796
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001797static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1798{
1799 free(o->data);
1800}
1801
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001802static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001803{
1804 if (o->length + len > o->maxlen) {
1805 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1806 o->data = xrealloc(o->data, 1 + o->maxlen);
1807 }
1808}
1809
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001810static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001811{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001812 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1813 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001814 o->data[o->length] = ch;
1815 o->length++;
1816 o->data[o->length] = '\0';
1817}
1818
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001819static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001820{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001821 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001822 memcpy(&o->data[o->length], str, len);
1823 o->length += len;
1824 o->data[o->length] = '\0';
1825}
1826
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001827#if !BB_MMU
1828static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001829{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001830 o_addblock(o, str, strlen(str));
1831}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001832static void nommu_addchr(o_string *o, int ch)
1833{
1834 if (o)
1835 o_addchr(o, ch);
1836}
1837#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001838# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001839#endif
1840
1841static void o_addstr_with_NUL(o_string *o, const char *str)
1842{
1843 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001844}
1845
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001846static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001847{
1848 while (len) {
1849 o_addchr(o, *str);
1850 if (*str++ == '\\'
1851 && (*str != '*' && *str != '?' && *str != '[')
1852 ) {
1853 o_addchr(o, '\\');
1854 }
1855 len--;
1856 }
1857}
1858
Eric Andersen25f27032001-04-26 23:22:31 +00001859/* My analysis of quoting semantics tells me that state information
1860 * is associated with a destination, not a source.
1861 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001862static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001863{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001864 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001865 char *found = strchr("*?[\\", ch);
1866 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001867 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001868 o_grow_by(o, sz);
1869 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001870 o->data[o->length] = '\\';
1871 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001872 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001873 o->data[o->length] = ch;
1874 o->length++;
1875 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001876}
1877
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001878static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001879{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001880 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001881 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001882 sz++;
1883 o->data[o->length] = '\\';
1884 o->length++;
1885 }
1886 o_grow_by(o, sz);
1887 o->data[o->length] = ch;
1888 o->length++;
1889 o->data[o->length] = '\0';
1890}
1891
1892static void o_addQstr(o_string *o, const char *str, int len)
1893{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001894 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001895 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001896 return;
1897 }
1898 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001899 char ch;
1900 int sz;
1901 int ordinary_cnt = strcspn(str, "*?[\\");
1902 if (ordinary_cnt > len) /* paranoia */
1903 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001904 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001905 if (ordinary_cnt == len)
1906 return;
1907 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001908 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001909
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001910 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001911 sz = 1;
1912 if (ch) { /* it is necessarily one of "*?[\\" */
1913 sz++;
1914 o->data[o->length] = '\\';
1915 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001916 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001917 o_grow_by(o, sz);
1918 o->data[o->length] = ch;
1919 o->length++;
1920 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001921 }
1922}
1923
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001924/* A special kind of o_string for $VAR and `cmd` expansion.
1925 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001926 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001927 * list[i] contains an INDEX (int!) into this string data.
1928 * It means that if list[] needs to grow, data needs to be moved higher up
1929 * but list[i]'s need not be modified.
1930 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001931 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001932 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1933 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001934#if DEBUG_EXPAND || DEBUG_GLOB
1935static void debug_print_list(const char *prefix, o_string *o, int n)
1936{
1937 char **list = (char**)o->data;
1938 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1939 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001940
1941 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001942 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1943 prefix, list, n, string_start, o->length, o->maxlen);
1944 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001945 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001946 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1947 o->data + (int)list[i] + string_start,
1948 o->data + (int)list[i] + string_start);
1949 i++;
1950 }
1951 if (n) {
1952 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001953 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001954 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001955 }
1956}
1957#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001958# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001959#endif
1960
1961/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1962 * in list[n] so that it points past last stored byte so far.
1963 * It returns n+1. */
1964static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001965{
1966 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001967 int string_start;
1968 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001969
1970 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001971 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1972 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001973 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001974 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001975 /* list[n] points to string_start, make space for 16 more pointers */
1976 o->maxlen += 0x10 * sizeof(list[0]);
1977 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001978 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001979 memmove(list + n + 0x10, list + n, string_len);
1980 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001981 } else {
1982 debug_printf_list("list[%d]=%d string_start=%d\n",
1983 n, string_len, string_start);
1984 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001985 } else {
1986 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001987 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1988 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001989 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1990 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001991 o->has_empty_slot = 0;
1992 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001993 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001994 return n + 1;
1995}
1996
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001997/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001998static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001999{
2000 char **list = (char**)o->data;
2001 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2002
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002003 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002004}
2005
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002006#undef HUSH_BRACE_EXP
2007/* There in a GNU extension, GLOB_BRACE, but it is not usable:
2008 * first, it processes even {a} (no commas), second,
2009 * I didn't manage to make it return strings when they don't match
2010 # existing files. Need to re-implement it.
2011 *
2012 * This code needs corresponding quoting on variable expansion side.
2013 * Currently, "a='{q,w}'; echo $a" erroneously expands braces in $a
2014 */
2015#ifdef HUSH_BRACE_EXP
2016/* Return pointer to next closing brace or to comma */
2017static const char *next_brace_sub(const char *cp)
2018{
2019 unsigned depth = 0;
2020 cp++;
2021 while (*cp != '\0') {
2022 if (*cp == '\\') {
2023 if (*++cp == '\0')
2024 break;
2025 cp++;
2026 continue;
2027 }
2028 /*{*/ if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2029 break;
2030 if (*cp++ == '{') /*}*/
2031 depth++;
2032 }
2033
2034 return *cp != '\0' ? cp : NULL;
2035}
2036static int glob_brace(const char *pattern, int flags, glob_t *pglob)
2037{
2038 const char *begin;
2039 char *alt_start;
2040 const char *p;
2041 const char *next;
2042 const char *rest;
2043 size_t rest_len;
2044 char *onealt;
2045
2046 debug_printf_glob("glob_brace('%s')\n", pattern);
2047
2048 begin = pattern;
2049 while (1) {
2050 if (*begin == '\0')
2051 goto do_glob;
2052 if (*begin == '{') /*}*/ {
2053 /* Find the first sub-pattern and at the same time
2054 * find the rest after the closing brace */
2055 next = next_brace_sub(begin);
2056 if (next == NULL) {
2057 /* An illegal expression */
2058 goto do_glob;
2059 }
2060 /*{*/ if (*next == '}') {
2061 /* "{abc}" with no commas - illegal
2062 * brace expr, disregard and skip it */
2063 begin = next + 1;
2064 continue;
2065 }
2066 break;
2067 }
2068 if (*begin == '\\' && begin[1] != '\0')
2069 begin++;
2070 begin++;
2071 }
2072 debug_printf_glob("begin:%s\n", begin);
2073 debug_printf_glob("next:%s\n", next);
2074
2075 /* Now find the end of the whole brace expression */
2076 rest = next;
2077 /*{*/ while (*rest != '}') {
2078 rest = next_brace_sub(rest);
2079 if (rest == NULL) {
2080 /* An illegal expression */
2081 goto do_glob;
2082 }
2083 debug_printf_glob("rest:%s\n", rest);
2084 }
2085 rest_len = strlen(++rest) + 1;
2086
2087 /* We are sure the brace expression is well-formed */
2088
2089 /* Allocate working buffer large enough for our work */
2090 onealt = alloca(strlen(pattern));
2091 /* We know the prefix for all sub-patterns */
2092 alt_start = mempcpy(onealt, pattern, begin - pattern);
2093
2094 /* We have a brace expression. BEGIN points to the opening {,
2095 * NEXT points past the terminator of the first element, and REST
2096 * points past the final }. We will accumulate result names from
2097 * recursive runs for each brace alternative in the buffer using
2098 * GLOB_APPEND. */
2099
2100 p = begin + 1;
2101 while (1) {
2102 int result;
2103
2104 /* Construct the new glob expression */
2105 memcpy(mempcpy(alt_start, p, next - p), rest, rest_len);
2106
2107 result = glob_brace(onealt, flags, pglob);
2108 /* If we got an error, return it */
2109 if (result && result != GLOB_NOMATCH)
2110 return result;
2111
2112 flags |= GLOB_APPEND;
2113
2114 /*{*/ if (*next == '}') {
2115 /* We saw the last entry */
2116 break;
2117 }
2118 p = next + 1;
2119 next = next_brace_sub(next);
2120 }
2121
2122 /* We found some entries */
2123 return 0;
2124
2125 do_glob:
2126 return glob(pattern, flags, NULL, pglob);
2127}
2128#endif
2129
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002130/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00002131 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002132static int o_glob(o_string *o, int n)
2133{
2134 glob_t globdata;
2135 int gr;
2136 char *pattern;
2137
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002138 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002139 if (!o->data)
2140 return o_save_ptr_helper(o, n);
2141 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002142 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002143 if (!glob_needed(pattern)) {
2144 literal:
2145 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002146 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002147 return o_save_ptr_helper(o, n);
2148 }
2149
2150 memset(&globdata, 0, sizeof(globdata));
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002151#ifdef HUSH_BRACE_EXP
2152 gr = glob_brace(pattern, GLOB_NOCHECK, &globdata);
2153 debug_printf_glob("glob_brace('%s'):%d\n", pattern, gr);
2154#else
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002155 gr = glob(pattern, 0, NULL, &globdata);
2156 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002157#endif
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002158 if (gr == GLOB_NOSPACE)
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002159 bb_error_msg_and_die(bb_msg_memory_exhausted);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002160 if (gr == GLOB_NOMATCH) {
2161 globfree(&globdata);
2162 goto literal;
2163 }
Denys Vlasenko5b2db972009-11-16 05:49:36 +01002164 if (gr != 0) {
2165 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2166 * but we didn't specify it. Paranoia again. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002167 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2168 }
2169 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2170 char **argv = globdata.gl_pathv;
2171 o->length = pattern - o->data; /* "forget" pattern */
2172 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002173 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002174 n = o_save_ptr_helper(o, n);
2175 argv++;
2176 if (!*argv)
2177 break;
2178 }
2179 }
2180 globfree(&globdata);
2181 if (DEBUG_GLOB)
2182 debug_print_list("o_glob returning", o, n);
2183 return n;
2184}
2185
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002186/* If o->o_glob == 1, glob the string so far remembered.
2187 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002188static int o_save_ptr(o_string *o, int n)
2189{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002190 if (o->o_glob) { /* if globbing is requested */
2191 /* If o->has_empty_slot, list[n] was already globbed
2192 * (if it was requested back then when it was filled)
2193 * so don't do that again! */
2194 if (!o->has_empty_slot)
2195 return o_glob(o, n); /* o_save_ptr_helper is inside */
2196 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002197 return o_save_ptr_helper(o, n);
2198}
2199
2200/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002201static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002202{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002203 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002204 int string_start;
2205
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002206 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2207 if (DEBUG_EXPAND)
2208 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002209 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002210 list = (char**)o->data;
2211 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2212 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002213 while (n) {
2214 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002215 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002216 }
2217 return list;
2218}
2219
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002220
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002221/* Expansion can recurse */
2222#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002223static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002224#endif
2225static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002226#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002227#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002228 parse_stream_dquoted(dest, input, dquote_end)
2229#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002230static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002231 o_string *dest,
2232 struct in_str *input,
2233 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002234
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002235/* expand_strvec_to_strvec() takes a list of strings, expands
2236 * all variable references within and returns a pointer to
2237 * a list of expanded strings, possibly with larger number
2238 * of strings. (Think VAR="a b"; echo $VAR).
2239 * This new list is allocated as a single malloc block.
2240 * NULL-terminated list of char* pointers is at the beginning of it,
2241 * followed by strings themself.
2242 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002243
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002244/* Store given string, finalizing the word and starting new one whenever
2245 * we encounter IFS char(s). This is used for expanding variable values.
2246 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2247static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002248{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002249 while (1) {
2250 int word_len = strcspn(str, G.ifs);
2251 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002252 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002253 o_addQstr(output, str, word_len);
2254 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002255 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002256 str += word_len;
2257 }
2258 if (!*str) /* EOL - do not finalize word */
2259 break;
2260 o_addchr(output, '\0');
2261 debug_print_list("expand_on_ifs", output, n);
2262 n = o_save_ptr(output, n);
2263 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002264 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002265 debug_print_list("expand_on_ifs[1]", output, n);
2266 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002267}
2268
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002269/* Helper to expand $((...)) and heredoc body. These act as if
2270 * they are in double quotes, with the exception that they are not :).
2271 * Just the rules are similar: "expand only $var and `cmd`"
2272 *
2273 * Returns malloced string.
2274 * As an optimization, we return NULL if expansion is not needed.
2275 */
2276static char *expand_pseudo_dquoted(const char *str)
2277{
2278 char *exp_str;
2279 struct in_str input;
2280 o_string dest = NULL_O_STRING;
2281
2282 if (strchr(str, '$') == NULL
2283#if ENABLE_HUSH_TICK
2284 && strchr(str, '`') == NULL
2285#endif
2286 ) {
2287 return NULL;
2288 }
2289
2290 /* We need to expand. Example:
2291 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2292 */
2293 setup_string_in_str(&input, str);
2294 parse_stream_dquoted(NULL, &dest, &input, EOF);
2295 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2296 exp_str = expand_string_to_string(dest.data);
2297 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2298 o_free_unsafe(&dest);
2299 return exp_str;
2300}
2301
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002302/* Expand all variable references in given string, adding words to list[]
2303 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2304 * to be filled). This routine is extremely tricky: has to deal with
2305 * variables/parameters with whitespace, $* and $@, and constructs like
2306 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002307static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002308{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002309 /* or_mask is either 0 (normal case) or 0x80 -
2310 * expansion of right-hand side of assignment == 1-element expand.
2311 * It will also do no globbing, and thus we must not backslash-quote!
2312 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002313 char ored_ch;
2314 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315
2316 ored_ch = 0;
2317
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002318 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002319 debug_print_list("expand_vars_to_list", output, n);
2320 n = o_save_ptr(output, n);
2321 debug_print_list("expand_vars_to_list[0]", output, n);
2322
2323 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002324 char first_ch;
2325 int i;
2326 char *dyn_val = NULL;
2327 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002328#if ENABLE_HUSH_TICK
2329 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002330#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002331#if ENABLE_SH_MATH_SUPPORT
2332 char arith_buf[sizeof(arith_t)*3 + 2];
2333#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002334 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002335 debug_print_list("expand_vars_to_list[1]", output, n);
2336 arg = ++p;
2337 p = strchr(p, SPECIAL_VAR_SYMBOL);
2338
2339 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2340 /* "$@" is special. Even if quoted, it can still
2341 * expand to nothing (not even an empty string) */
2342 if ((first_ch & 0x7f) != '@')
2343 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002344
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345 switch (first_ch & 0x7f) {
2346 /* Highest bit in first_ch indicates that var is double-quoted */
2347 case '$': /* pid */
2348 val = utoa(G.root_pid);
2349 break;
2350 case '!': /* bg pid */
2351 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2352 break;
2353 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002354 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002355 break;
2356 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002357 if (arg[1] != SPECIAL_VAR_SYMBOL)
2358 /* actually, it's a ${#var} */
2359 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002360 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2361 break;
2362 case '*':
2363 case '@':
2364 i = 1;
2365 if (!G.global_argv[i])
2366 break;
2367 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2368 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002369 smallint sv = output->o_escape;
2370 /* unquoted var's contents should be globbed, so don't escape */
2371 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002372 while (G.global_argv[i]) {
2373 n = expand_on_ifs(output, n, G.global_argv[i]);
2374 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2375 if (G.global_argv[i++][0] && G.global_argv[i]) {
2376 /* this argv[] is not empty and not last:
2377 * put terminating NUL, start new word */
2378 o_addchr(output, '\0');
2379 debug_print_list("expand_vars_to_list[2]", output, n);
2380 n = o_save_ptr(output, n);
2381 debug_print_list("expand_vars_to_list[3]", output, n);
2382 }
2383 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002384 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002385 } else
2386 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2387 * and in this case should treat it like '$*' - see 'else...' below */
2388 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2389 while (1) {
2390 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2391 if (++i >= G.global_argc)
2392 break;
2393 o_addchr(output, '\0');
2394 debug_print_list("expand_vars_to_list[4]", output, n);
2395 n = o_save_ptr(output, n);
2396 }
2397 } else { /* quoted $*: add as one word */
2398 while (1) {
2399 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2400 if (!G.global_argv[++i])
2401 break;
2402 if (G.ifs[0])
2403 o_addchr(output, G.ifs[0]);
2404 }
2405 }
2406 break;
2407 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2408 /* "Empty variable", used to make "" etc to not disappear */
2409 arg++;
2410 ored_ch = 0x80;
2411 break;
2412#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002413 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002414 *p = '\0';
2415 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002416 /* Can't just stuff it into output o_string,
2417 * expanded result may need to be globbed
2418 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002419 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denys Vlasenko647553a2009-11-15 19:58:19 +01002420 G.last_exitcode = process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002421 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2422 val = subst_result.data;
2423 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002424#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002425#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002426 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002427 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002428 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002429 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002430 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002431
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002432 arg++; /* skip '+' */
2433 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002434 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002435
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002436 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002437 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002438 hooks.setvar = arith_set_local_var;
2439 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002440 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2441 free(exp_str);
2442
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002443 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002444 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002445 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002446 case -3:
2447 msg = "exponent less than 0";
2448 break;
2449 case -2:
2450 msg = "divide by 0";
2451 break;
2452 case -5:
2453 msg = "expression recursion loop detected";
2454 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002455 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002456 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002457 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002458 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002459 sprintf(arith_buf, arith_t_fmt, res);
2460 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002461 break;
2462 }
2463#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002464 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002465 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002466 bool exp_len = false;
2467 bool exp_null = false;
2468 char *var = arg;
2469 char exp_save = exp_save; /* for compiler */
2470 char exp_op = exp_op; /* for compiler */
2471 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002472 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002473
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002474 *p = '\0';
2475 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002476
2477 /* prepare for expansions */
2478 if (var[0] == '#') {
2479 /* handle length expansion ${#var} */
2480 exp_len = true;
2481 ++var;
2482 } else {
2483 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002484 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002485 if (!var[exp_off])
2486 exp_off = 0;
2487 if (exp_off) {
2488 exp_save = var[exp_off];
2489 exp_null = exp_save == ':';
2490 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002491 if (exp_null)
2492 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002493 exp_op = *exp_word++;
2494 var[exp_off] = '\0';
2495 }
2496 }
2497
2498 /* lookup the variable in question */
2499 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002500 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002501 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002502 if (i < G.global_argc)
2503 val = G.global_argv[i];
2504 /* else val remains NULL: $N with too big N */
2505 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002506 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002507
2508 /* handle any expansions */
2509 if (exp_len) {
2510 debug_printf_expand("expand: length of '%s' = ", val);
2511 val = utoa(val ? strlen(val) : 0);
2512 debug_printf_expand("%s\n", val);
2513 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002514 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002515 if (val) {
2516 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002517 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002518 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002519 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002520 if (exp_op == *exp_word) /* ## or %% */
2521 ++exp_word;
2522 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002523 loc = scan(dyn_val, exp_word, match_at_left);
2524 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002525 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002526 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002527 *loc = '\0';
2528 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002529 } else {
2530 /* we need to do an expansion */
2531 int exp_test = (!val || (exp_null && !val[0]));
2532 if (exp_op == '+')
2533 exp_test = !exp_test;
2534 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2535 exp_null ? "true" : "false", exp_test);
2536 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002537 if (exp_op == '?') {
2538//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002539 /* ${var?[error_msg_if_unset]} */
2540 /* ${var:?[error_msg_if_unset_or_null]} */
2541 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002542 die_if_script("%s: %s",
2543 var,
2544 exp_word[0] ? exp_word : "parameter null or not set"
2545 );
2546 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002547 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002548 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002549
Mike Frysingera4f331d2009-04-07 06:03:22 +00002550 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002551 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002552 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002553 /* mimic bash message */
2554 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002555 val = NULL;
2556 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002557 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002558 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002559 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002560 }
2561 }
2562 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002563
Mike Frysinger6379bb42009-03-28 18:55:03 +00002564 var[exp_off] = exp_save;
2565 }
2566
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002567 arg[0] = first_ch;
2568#if ENABLE_HUSH_TICK
2569 store_val:
2570#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002571 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002572 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002573 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002574 /* unquoted var's contents should be globbed, so don't escape */
2575 smallint sv = output->o_escape;
2576 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577 n = expand_on_ifs(output, n, val);
2578 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002579 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580 }
2581 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002582 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002583 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002584 } /* default: */
2585 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002586
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002587 if (val) {
2588 o_addQstr(output, val, strlen(val));
2589 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002590 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002591 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002592 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002593 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002594
2595#if ENABLE_HUSH_TICK
2596 o_free(&subst_result);
2597#endif
2598 arg = ++p;
2599 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2600
2601 if (arg[0]) {
2602 debug_print_list("expand_vars_to_list[a]", output, n);
2603 /* this part is literal, and it was already pre-quoted
2604 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002605 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002606 debug_print_list("expand_vars_to_list[b]", output, n);
2607 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2608 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2609 ) {
2610 n--;
2611 /* allow to reuse list[n] later without re-growth */
2612 output->has_empty_slot = 1;
2613 } else {
2614 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002615 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002616 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002617}
2618
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002619static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002620{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002621 int n;
2622 char **list;
2623 char **v;
2624 o_string output = NULL_O_STRING;
2625
2626 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002627 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002628 /* (unquoted $var will temporarily switch it off) */
2629 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002630 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002631
2632 n = 0;
2633 v = argv;
2634 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002635 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002636 v++;
2637 }
2638 debug_print_list("expand_variables", &output, n);
2639
2640 /* output.data (malloced in one block) gets returned in "list" */
2641 list = o_finalize_list(&output, n);
2642 debug_print_strings("expand_variables[1]", list);
2643 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002644}
2645
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002646static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002647{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002648 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002649}
2650
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002651#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002652static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2653{
2654 return expand_variables(argv, 0x80);
2655}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002656#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002657
2658#ifdef CMD_SINGLEWORD_NOGLOB_COND
2659static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2660{
2661 int n;
2662 char **list;
2663 char **v;
2664 o_string output = NULL_O_STRING;
2665
2666 n = 0;
2667 v = argv;
2668 while (*v) {
2669 int is_var = is_well_formed_var_name(*v, '=');
2670 /* is_var * 0x80: singleword expansion for vars */
2671 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2672
2673 /* Subtle! expand_vars_to_list did not glob last word yet.
2674 * It does this only when fed with further data.
2675 * Therefore we set globbing flags AFTER it, not before:
2676 */
2677
2678 /* if it is not recognizably abc=...; then: */
2679 output.o_escape = !is_var; /* protect against globbing for "$var" */
2680 /* (unquoted $var will temporarily switch it off) */
2681 output.o_glob = !is_var; /* and indeed do globbing */
2682 v++;
2683 }
2684 debug_print_list("expand_cond", &output, n);
2685
2686 /* output.data (malloced in one block) gets returned in "list" */
2687 list = o_finalize_list(&output, n);
2688 debug_print_strings("expand_cond[1]", list);
2689 return list;
2690}
2691#endif
2692
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002693/* Used for expansion of right hand of assignments */
2694/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2695 * "v=/bin/c*" */
2696static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002697{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002698 char *argv[2], **list;
2699
2700 argv[0] = (char*)str;
2701 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002702 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002703 if (HUSH_DEBUG)
2704 if (!list[0] || list[1])
2705 bb_error_msg_and_die("BUG in varexp2");
2706 /* actually, just move string 2*sizeof(char*) bytes back */
2707 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002708 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002709 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2710 return (char*)list;
2711}
2712
2713/* Used for "eval" builtin */
2714static char* expand_strvec_to_string(char **argv)
2715{
2716 char **list;
2717
2718 list = expand_variables(argv, 0x80);
2719 /* Convert all NULs to spaces */
2720 if (list[0]) {
2721 int n = 1;
2722 while (list[n]) {
2723 if (HUSH_DEBUG)
2724 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2725 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002726 /* bash uses ' ' regardless of $IFS contents */
2727 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002728 n++;
2729 }
2730 }
2731 overlapping_strcpy((char*)list, list[0]);
2732 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2733 return (char*)list;
2734}
2735
2736static char **expand_assignments(char **argv, int count)
2737{
2738 int i;
2739 char **p = NULL;
2740 /* Expand assignments into one string each */
2741 for (i = 0; i < count; i++) {
2742 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2743 }
2744 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002745}
2746
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002747
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002748#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002749/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002750void re_execute_shell(char ***to_free, const char *s,
2751 char *g_argv0, char **g_argv,
2752 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002753
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002754static void reset_traps_to_defaults(void)
2755{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002756 /* This function is always called in a child shell
2757 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002758 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002759 unsigned sig;
2760 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002761
Denys Vlasenko67f71862009-09-25 14:21:06 +02002762 /* Child shells are not interactive.
2763 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2764 * Testcase: (while :; do :; done) + ^Z should background.
2765 * Same goes for SIGTERM, SIGHUP, SIGINT.
2766 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002767 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002768 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002769
Denys Vlasenko67f71862009-09-25 14:21:06 +02002770 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2771 * Stupid. It can be done with *single* &= op, but we can't use
2772 * the fact that G.blocked_set is implemented as a bitmask
2773 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002774 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2775 sig = 1;
2776 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002777 if (mask & 1) {
2778 /* Careful. Only if no trap or trap is not "" */
2779 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2780 sigdelset(&G.blocked_set, sig);
2781 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002782 mask >>= 1;
2783 if (!mask)
2784 break;
2785 sig++;
2786 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002787 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002788 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002789
2790 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002791 mask = G.non_DFL_mask;
2792 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002793 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002794 continue;
2795 free(G.traps[sig]);
2796 G.traps[sig] = NULL;
2797 /* There is no signal for 0 (EXIT) */
2798 if (sig == 0)
2799 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002800 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002801 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02002802 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002803 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002804 continue;
2805 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002806 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002807 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002808}
2809
2810#else /* !BB_MMU */
2811
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002812static void re_execute_shell(char ***to_free, const char *s,
2813 char *g_argv0, char **g_argv,
2814 char **builtin_argv) NORETURN;
2815static void re_execute_shell(char ***to_free, const char *s,
2816 char *g_argv0, char **g_argv,
2817 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002818{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002819 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002820 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002821 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002822# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002823 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002824# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002825 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002826 unsigned cnt;
2827
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002828 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002829 argv = heredoc_argv;
2830 argv[0] = (char *) G.argv0_for_re_execing;
2831 argv[1] = (char *) "-<";
2832 argv[2] = (char *) s;
2833 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002834 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002835 goto do_exec;
2836 }
2837
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002838 cnt = 0;
2839 pp = builtin_argv;
2840 if (pp) while (*pp++)
2841 cnt++;
2842
Denys Vlasenkodea47882009-10-09 15:40:49 +02002843 sprintf(param_buf, "-$%x:%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002844 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02002845 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002846 , (unsigned) G.last_bg_pid
2847 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002848 , cnt
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002849 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002850 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002851 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002852 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002853 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002854 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002855 for (cur = G.top_var; cur; cur = cur->next) {
2856 if (!cur->flg_export || cur->flg_read_only)
2857 cnt += 2;
2858 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002859# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002860 for (funcp = G.top_func; funcp; funcp = funcp->next)
2861 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002862# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002863 pp = g_argv;
2864 while (*pp++)
2865 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002866 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002867 *pp++ = (char *) G.argv0_for_re_execing;
2868 *pp++ = param_buf;
2869 for (cur = G.top_var; cur; cur = cur->next) {
2870 if (cur->varstr == hush_version_str)
2871 continue;
2872 if (cur->flg_read_only) {
2873 *pp++ = (char *) "-R";
2874 *pp++ = cur->varstr;
2875 } else if (!cur->flg_export) {
2876 *pp++ = (char *) "-V";
2877 *pp++ = cur->varstr;
2878 }
2879 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002880# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002881 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2882 *pp++ = (char *) "-F";
2883 *pp++ = funcp->name;
2884 *pp++ = funcp->body_as_string;
2885 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002886# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002887 /* We can pass activated traps here. Say, -Tnn:trap_string
2888 *
2889 * However, POSIX says that subshells reset signals with traps
2890 * to SIG_DFL.
2891 * I tested bash-3.2 and it not only does that with true subshells
2892 * of the form ( list ), but with any forked children shells.
2893 * I set trap "echo W" WINCH; and then tried:
2894 *
2895 * { echo 1; sleep 20; echo 2; } &
2896 * while true; do echo 1; sleep 20; echo 2; break; done &
2897 * true | { echo 1; sleep 20; echo 2; } | cat
2898 *
2899 * In all these cases sending SIGWINCH to the child shell
2900 * did not run the trap. If I add trap "echo V" WINCH;
2901 * _inside_ group (just before echo 1), it works.
2902 *
2903 * I conclude it means we don't need to pass active traps here.
2904 * exec syscall below resets them to SIG_DFL for us.
2905 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002906 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002907 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002908 if (builtin_argv) {
2909 while (*++builtin_argv)
2910 *pp++ = *builtin_argv;
2911 *pp++ = (char *) "";
2912 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002913 *pp++ = g_argv0;
2914 while (*g_argv)
2915 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002916 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002917 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002918
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002919 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002920 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2921 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002922 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002923 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002924 if (argv[0][0] == '/')
2925 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002926 xfunc_error_retval = 127;
2927 bb_error_msg_and_die("can't re-execute the shell");
2928}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002929#endif /* !BB_MMU */
2930
2931
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002932static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002933{
2934 struct fd_pair pair;
2935 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002936 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002937 /* the _body_ of heredoc (misleading field name) */
2938 const char *heredoc = redir->rd_filename;
2939 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002940#if !BB_MMU
2941 char **to_free;
2942#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002943
2944 expanded = NULL;
2945 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2946 expanded = expand_pseudo_dquoted(heredoc);
2947 if (expanded)
2948 heredoc = expanded;
2949 }
2950 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002951
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002952 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002953 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002954 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002955
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002956 /* Try writing without forking. Newer kernels have
2957 * dynamically growing pipes. Must use non-blocking write! */
2958 ndelay_on(pair.wr);
2959 while (1) {
2960 written = write(pair.wr, heredoc, len);
2961 if (written <= 0)
2962 break;
2963 len -= written;
2964 if (len == 0) {
2965 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002966 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002967 return;
2968 }
2969 heredoc += written;
2970 }
2971 ndelay_off(pair.wr);
2972
2973 /* Okay, pipe buffer was not big enough */
2974 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002975 * for the unsuspecting parent process. Child creates a grandchild
2976 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002977 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002978#if !BB_MMU
2979 to_free = NULL;
2980#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002981 pid = vfork();
2982 if (pid < 0)
2983 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002984 if (pid == 0) {
2985 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002986 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002987 pid = BB_MMU ? fork() : vfork();
2988 if (pid < 0)
2989 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2990 if (pid != 0)
2991 _exit(0);
2992 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002993 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002994#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002995 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002996 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002997#else
2998 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002999 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003000 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00003001#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003002 }
3003 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003004#if ENABLE_HUSH_FAST
3005 G.count_SIGCHLD++;
3006//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3007#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003008 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003009#if !BB_MMU
3010 free(to_free);
3011#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003012 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003013 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003014 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003015}
3016
Eric Andersen25f27032001-04-26 23:22:31 +00003017/* squirrel != NULL means we squirrel away copies of stdin, stdout,
3018 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003019static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00003020{
3021 int openfd, mode;
3022 struct redir_struct *redir;
3023
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003024 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003025 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003026 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003027 if (squirrel && redir->rd_fd < 3
3028 && squirrel[redir->rd_fd] < 0
3029 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003030 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003031 }
3032 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
3033 * of the heredoc */
3034 debug_printf_parse("set heredoc '%s'\n",
3035 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003036 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00003037 continue;
3038 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003039
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003040 if (redir->rd_dup == REDIRFD_TO_FILE) {
3041 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003042 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003043 if (redir->rd_filename == NULL) {
3044 /* Something went wrong in the parse.
3045 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003046 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003047 continue;
3048 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003049 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003050 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00003051 openfd = open_or_warn(p, mode);
3052 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00003053 if (openfd < 0) {
3054 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003055 * bash and ash both lose it as well (though zsh doesn't!) */
3056//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00003057 return 1;
3058 }
3059 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003060 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003061 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00003062 }
3063
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003064 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02003065 if (squirrel && redir->rd_fd < 3
3066 && squirrel[redir->rd_fd] < 0
3067 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003068 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00003069 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003070 if (openfd == REDIRFD_CLOSE) {
3071 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003072 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003073 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003074 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003075 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003076 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003077 }
Eric Andersen25f27032001-04-26 23:22:31 +00003078 }
3079 }
3080 return 0;
3081}
3082
3083static void restore_redirects(int squirrel[])
3084{
3085 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003086 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00003087 fd = squirrel[i];
3088 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003089 /* We simply die on error */
3090 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00003091 }
3092 }
3093}
3094
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003095
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003096static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003097
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003098/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003099static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003100{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003101 char **p;
3102 struct command *command;
3103 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003104 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003105
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003106 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003107 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003108 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003109 for (i = 0; i < pi->num_cmds; i++) {
3110 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003111 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003112 if (command->argv) {
3113 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003114 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003115 }
3116 free_strings(command->argv);
3117 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003118 }
3119 /* not "else if": on syntax error, we may have both! */
3120 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003121 debug_printf_clean(" begin group (cmd_type:%d)\n",
3122 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003123 free_pipe_list(command->group);
3124 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003125 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003126 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00003127 /* else is crucial here.
3128 * If group != NULL, child_func is meaningless */
3129#if ENABLE_HUSH_FUNCTIONS
3130 else if (command->child_func) {
3131 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3132 command->child_func->parent_cmd = NULL;
3133 }
3134#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003135#if !BB_MMU
3136 free(command->group_as_string);
3137 command->group_as_string = NULL;
3138#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003139 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003140 debug_printf_clean(" redirect %d%s",
3141 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003142 /* guard against the case >$FOO, where foo is unset or blank */
3143 if (r->rd_filename) {
3144 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3145 free(r->rd_filename);
3146 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003147 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003148 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003149 rnext = r->next;
3150 free(r);
3151 }
3152 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003153 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003154 free(pi->cmds); /* children are an array, they get freed all at once */
3155 pi->cmds = NULL;
3156#if ENABLE_HUSH_JOB
3157 free(pi->cmdtext);
3158 pi->cmdtext = NULL;
3159#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003160}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003161
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003162static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003163{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003164 struct pipe *pi, *next;
3165
3166 for (pi = head; pi; pi = next) {
3167#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003168 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003169#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003170 free_pipe(pi);
3171 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003172 next = pi->next;
3173 /*pi->next = NULL;*/
3174 free(pi);
3175 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003176}
3177
3178
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003179static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003180#if BB_MMU
3181#define parse_stream(pstring, input, end_trigger) \
3182 parse_stream(input, end_trigger)
3183#endif
3184static struct pipe *parse_stream(char **pstring,
3185 struct in_str *input,
3186 int end_trigger);
3187static void parse_and_run_string(const char *s);
3188
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003189
Mike Frysinger93cadc22009-05-27 17:06:25 -04003190static char *find_in_path(const char *arg)
3191{
3192 char *ret = NULL;
3193 const char *PATH = get_local_var_value("PATH");
3194
3195 if (!PATH)
3196 return NULL;
3197
3198 while (1) {
3199 const char *end = strchrnul(PATH, ':');
3200 int sz = end - PATH; /* must be int! */
3201
3202 free(ret);
3203 if (sz != 0) {
3204 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3205 } else {
3206 /* We have xxx::yyyy in $PATH,
3207 * it means "use current dir" */
3208 ret = xstrdup(arg);
3209 }
3210 if (access(ret, F_OK) == 0)
3211 break;
3212
3213 if (*end == '\0') {
3214 free(ret);
3215 return NULL;
3216 }
3217 PATH = end + 1;
3218 }
3219
3220 return ret;
3221}
3222
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003223static const struct built_in_command* find_builtin_helper(const char *name,
3224 const struct built_in_command *x,
3225 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003226{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003227 while (x != end) {
3228 if (strcmp(name, x->cmd) != 0) {
3229 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003230 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003231 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003232 debug_printf_exec("found builtin '%s'\n", name);
3233 return x;
3234 }
3235 return NULL;
3236}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003237static const struct built_in_command* find_builtin1(const char *name)
3238{
3239 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3240}
3241static const struct built_in_command* find_builtin(const char *name)
3242{
3243 const struct built_in_command *x = find_builtin1(name);
3244 if (x)
3245 return x;
3246 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3247}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003248
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003249#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003250static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003251{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003252 struct function **funcpp = &G.top_func;
3253 while (*funcpp) {
3254 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003255 break;
3256 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003257 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003258 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003259 return funcpp;
3260}
3261
3262static const struct function *find_function(const char *name)
3263{
3264 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003265 if (funcp)
3266 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003267 return funcp;
3268}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003269
Denis Vlasenkobc569742009-04-12 20:35:19 +00003270/* Note: takes ownership on name ptr */
3271static struct function *new_function(char *name)
3272{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003273 struct function **funcpp = find_function_slot(name);
3274 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003275
Denys Vlasenko873273d2009-09-12 14:47:41 +02003276 if (funcp != NULL) {
3277 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003278 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3279 if (!cmd) {
3280 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3281 free(funcp->name);
3282 /* Note: if !funcp->body, do not free body_as_string!
3283 * This is a special case of "-F name body" function:
3284 * body_as_string was not malloced! */
3285 if (funcp->body) {
3286 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003287# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003288 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003289# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003290 }
3291 } else {
3292 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3293 cmd->argv[0] = funcp->name;
3294 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003295# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003296 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003297# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003298 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003299 } else {
3300 debug_printf_exec("remembering new function '%s'\n", name);
3301 funcp = *funcpp = xzalloc(sizeof(*funcp));
3302 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003303 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003304
Denis Vlasenkobc569742009-04-12 20:35:19 +00003305 funcp->name = name;
3306 return funcp;
3307}
3308
Denis Vlasenko40e84372009-04-18 11:23:38 +00003309static void unset_func(const char *name)
3310{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003311 struct function **funcpp = find_function_slot(name);
3312 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003313
Denys Vlasenko873273d2009-09-12 14:47:41 +02003314 if (funcp != NULL) {
3315 debug_printf_exec("freeing function '%s'\n", funcp->name);
3316 *funcpp = funcp->next;
3317 /* funcp is unlinked now, deleting it.
3318 * Note: if !funcp->body, the function was created by
3319 * "-F name body", do not free ->body_as_string
3320 * and ->name as they were not malloced. */
3321 if (funcp->body) {
3322 free_pipe_list(funcp->body);
3323 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003324# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003325 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003326# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003327 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003328 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003329 }
3330}
3331
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003332# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003333#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003334 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003335# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003336static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003337 const struct function *funcp,
3338 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003339static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003340 const struct function *funcp,
3341 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003342{
3343# if BB_MMU
3344 int n = 1;
3345
3346 argv[0] = G.global_argv[0];
3347 G.global_argv = argv;
3348 while (*++argv)
3349 n++;
3350 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003351 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003352 n = run_list(funcp->body);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003353 fflush_all();
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003354 _exit(n);
3355# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003356 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003357 funcp->body_as_string,
3358 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003359 argv + 1,
3360 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003361# endif
3362}
3363
3364static int run_function(const struct function *funcp, char **argv)
3365{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003366 int rc;
3367 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003368 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003369
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003370 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003371
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003372 /* "we are in function, ok to use return" */
3373 sv_flg = G.flag_return_in_progress;
3374 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003375# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003376 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003377# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003378
Denis Vlasenkobc569742009-04-12 20:35:19 +00003379 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003380# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003381 if (!funcp->body) {
3382 /* Function defined by -F */
3383 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003384 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003385 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003386# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003387 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003388 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003389 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003390
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003391# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003392 {
3393 struct variable *var;
3394 struct variable **var_pp;
3395
3396 var_pp = &G.top_var;
3397 while ((var = *var_pp) != NULL) {
3398 if (var->func_nest_level < G.func_nest_level) {
3399 var_pp = &var->next;
3400 continue;
3401 }
3402 /* Unexport */
3403 if (var->flg_export)
3404 bb_unsetenv(var->varstr);
3405 /* Remove from global list */
3406 *var_pp = var->next;
3407 /* Free */
3408 if (!var->max_len)
3409 free(var->varstr);
3410 free(var);
3411 }
3412 G.func_nest_level--;
3413 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003414# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003415 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003416
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003417 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003418
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003419 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003420}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003421#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003422
3423
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003424#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003425#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003426 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003427#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003428#define exec_builtin(to_free, x, argv) \
3429 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003430#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003431static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003432 const struct built_in_command *x,
3433 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003434static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003435 const struct built_in_command *x,
3436 char **argv)
3437{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003438#if BB_MMU
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003439 int rcode = x->function(argv);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01003440 fflush_all();
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003441 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003442#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003443 /* On NOMMU, we must never block!
3444 * Example: { sleep 99 | read line; } & echo Ok
3445 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003446 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003447 argv[0],
3448 G.global_argv[0],
3449 G.global_argv + 1,
3450 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003451#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003452}
3453
3454
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003455static void execvp_or_die(char **argv) NORETURN;
3456static void execvp_or_die(char **argv)
3457{
3458 debug_printf_exec("execing '%s'\n", argv[0]);
3459 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3460 execvp(argv[0], argv);
3461 bb_perror_msg("can't execute '%s'", argv[0]);
3462 _exit(127); /* bash compat */
3463}
3464
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003465#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003466#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3467 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3468#define pseudo_exec(nommu_save, command, argv_expanded) \
3469 pseudo_exec(command, argv_expanded)
3470#endif
3471
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003472/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003473 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003474 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003475 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003476 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003477static void pseudo_exec_argv(nommu_save_t *nommu_save,
3478 char **argv, int assignment_cnt,
3479 char **argv_expanded) NORETURN;
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003480static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003481 char **argv, int assignment_cnt,
3482 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003483{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003484 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003485
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003486 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003487 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003488 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003489
Denis Vlasenko9504e442008-10-29 01:19:15 +00003490 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003491#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003492 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003493 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003494 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003495 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003496#else
3497 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003498 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003499#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003500 if (argv_expanded) {
3501 argv = argv_expanded;
3502 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003503 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003504#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003505 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003506#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003507 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003508
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003509#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3510 if (strchr(argv[0], '/') != NULL)
3511 goto skip;
3512#endif
3513
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003514 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003515 * Depending on context, this might be redundant. But it's
3516 * easier to waste a few CPU cycles than it is to figure out
3517 * if this is one of those cases.
3518 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003519 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003520 /* On NOMMU, it is more expensive to re-execute shell
3521 * just in order to run echo or test builtin.
3522 * It's better to skip it here and run corresponding
3523 * non-builtin later. */
3524 const struct built_in_command *x;
3525 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003526 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003527 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003528 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003529 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003530#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003531 /* Check if the command matches any functions */
3532 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003533 const struct function *funcp = find_function(argv[0]);
3534 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003535 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003536 }
3537 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003538#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003539
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003540#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003541 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003542 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003543 int a = find_applet_by_name(argv[0]);
3544 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003545# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003546 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003547 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003548 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003549 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003550# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003551 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003552 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003553 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3554 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003555 /* If they called chroot or otherwise made the binary no longer
3556 * executable, fall through */
3557 }
3558 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003559#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003560
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003561#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003562 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003563#endif
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02003564 execvp_or_die(argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003565}
3566
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003567/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003568 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003569static void pseudo_exec(nommu_save_t *nommu_save,
3570 struct command *command,
3571 char **argv_expanded) NORETURN;
3572static void pseudo_exec(nommu_save_t *nommu_save,
3573 struct command *command,
3574 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003575{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003576 if (command->argv) {
3577 pseudo_exec_argv(nommu_save, command->argv,
3578 command->assignment_cnt, argv_expanded);
3579 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003580
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003581 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003582 /* Cases when we are here:
3583 * ( list )
3584 * { list } &
3585 * ... | ( list ) | ...
3586 * ... | { list } | ...
3587 */
3588#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003589 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003590 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003591 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003592 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003593 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003594 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003595 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003596#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003597 re_execute_shell(&nommu_save->argv_from_re_execing,
3598 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003599 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003600 G.global_argv + 1,
3601 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003602#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003603 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003604
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003605 /* Case when we are here: ... | >file */
3606 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003607 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003608}
3609
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003610#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003611static const char *get_cmdtext(struct pipe *pi)
3612{
3613 char **argv;
3614 char *p;
3615 int len;
3616
3617 /* This is subtle. ->cmdtext is created only on first backgrounding.
3618 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003619 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003620 if (pi->cmdtext)
3621 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003622 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003623 if (!argv || !argv[0]) {
3624 pi->cmdtext = xzalloc(1);
3625 return pi->cmdtext;
3626 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003627
3628 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003629 do {
3630 len += strlen(*argv) + 1;
3631 } while (*++argv);
3632 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003633 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003634 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003635 do {
3636 len = strlen(*argv);
3637 memcpy(p, *argv, len);
3638 p += len;
3639 *p++ = ' ';
3640 } while (*++argv);
3641 p[-1] = '\0';
3642 return pi->cmdtext;
3643}
3644
Eric Andersenbafd94f2001-05-02 16:11:59 +00003645static void insert_bg_job(struct pipe *pi)
3646{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003647 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003648 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003649
3650 /* Linear search for the ID of the job to use */
3651 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003652 for (job = G.job_list; job; job = job->next)
3653 if (job->jobid >= pi->jobid)
3654 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003655
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003656 /* Add job to the list of running jobs */
3657 jobp = &G.job_list;
3658 while ((job = *jobp) != NULL)
3659 jobp = &job->next;
3660 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003661
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003662 *job = *pi; /* physical copy */
3663 job->next = NULL;
3664 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3665 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003666 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003667 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003668 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003669 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003670 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003671
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003672 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003673 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3674 /* Last command's pid goes to $! */
3675 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3676 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003677}
3678
Eric Andersenbafd94f2001-05-02 16:11:59 +00003679static void remove_bg_job(struct pipe *pi)
3680{
3681 struct pipe *prev_pipe;
3682
Denis Vlasenko87a86552008-07-29 19:43:10 +00003683 if (pi == G.job_list) {
3684 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003685 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003686 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003687 while (prev_pipe->next != pi)
3688 prev_pipe = prev_pipe->next;
3689 prev_pipe->next = pi->next;
3690 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003691 if (G.job_list)
3692 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003693 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003694 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003695}
Eric Andersen028b65b2001-06-28 01:10:11 +00003696
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003697/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003698static void delete_finished_bg_job(struct pipe *pi)
3699{
3700 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003701 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003702 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003703 free(pi);
3704}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003705#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003706
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003707/* Check to see if any processes have exited -- if they
3708 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003709static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003710{
Eric Andersenc798b072001-06-22 06:23:03 +00003711 int attributes;
3712 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003713#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003714 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003715#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003716 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003717 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003718
Denis Vlasenkod5762932009-03-31 11:22:57 +00003719 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3720
Eric Andersenc798b072001-06-22 06:23:03 +00003721 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003722 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003723 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003724
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003725 errno = 0;
3726#if ENABLE_HUSH_FAST
3727 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3728//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3729//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003730 /* There was neither fork nor SIGCHLD since last waitpid */
3731 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003732 if (!G.we_have_children) {
3733 errno = ECHILD;
3734 return -1;
3735 }
3736 if (fg_pipe == NULL) { /* is WNOHANG set? */
3737 /* We have children, but they did not exit
3738 * or stop yet (we saw no SIGCHLD) */
3739 return 0;
3740 }
3741 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3742 }
3743#endif
3744
Denis Vlasenko1359da62007-04-21 23:27:30 +00003745/* Do we do this right?
3746 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003747 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003748 * [3]+ Stopped sleep 20 | false
3749 * bash-3.00# echo $?
3750 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003751 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003752 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003753 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003754 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003755 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003756 int dead;
3757
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003758#if ENABLE_HUSH_FAST
3759 i = G.count_SIGCHLD;
3760#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003761 childpid = waitpid(-1, &status, attributes);
3762 if (childpid <= 0) {
3763 if (childpid && errno != ECHILD)
3764 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003765#if ENABLE_HUSH_FAST
3766 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003767 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003768 G.handled_SIGCHLD = i;
3769//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3770 }
3771#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003772 break;
3773 }
3774 dead = WIFEXITED(status) || WIFSIGNALED(status);
3775
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003776#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003777 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003778 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003779 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3780 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003781 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003782 childpid, WTERMSIG(status), WEXITSTATUS(status));
3783 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003784 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003785 childpid, WEXITSTATUS(status));
3786#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003787 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003788 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003789 for (i = 0; i < fg_pipe->num_cmds; i++) {
3790 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3791 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003792 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003793 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003794 fg_pipe->cmds[i].pid = 0;
3795 fg_pipe->alive_cmds--;
3796 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003797 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003798 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003799 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003800 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003801 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00003802 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003803 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003804 */
3805 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003806 int sig = WTERMSIG(status);
3807 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003808 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003809 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003810 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003811 fg_pipe->cmds[i].is_stopped = 1;
3812 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003813 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003814 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3815 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3816 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003817 /* All processes in fg pipe have exited or stopped */
3818/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3819 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3820 * and "killall -STOP cat" */
3821 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003822#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003823 if (fg_pipe->alive_cmds)
3824 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003825#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003826 return rcode;
3827 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02003828 if (!fg_pipe->alive_cmds)
3829 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003830 }
3831 /* There are still running processes in the fg pipe */
3832 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003833 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003834 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003835 }
3836
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003837#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003838 /* We asked to wait for bg or orphaned children */
3839 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003840 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003841 for (i = 0; i < pi->num_cmds; i++) {
3842 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003843 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003844 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003845 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003846 /* Happens when shell is used as init process (init=/bin/sh) */
3847 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003848 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003849
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003850 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003851 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003852 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003853 pi->cmds[i].pid = 0;
3854 pi->alive_cmds--;
3855 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003856 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003857 printf(JOB_STATUS_FORMAT, pi->jobid,
3858 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003859 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003860 }
3861 } else {
3862 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003863 pi->cmds[i].is_stopped = 1;
3864 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003865 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003866#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003867 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003868
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003869 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003870}
3871
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003872#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003873static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3874{
3875 pid_t p;
3876 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003877 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003878 /* Job finished, move the shell to the foreground */
3879 p = getpgrp(); /* our process group id */
3880 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3881 tcsetpgrp(G_interactive_fd, p);
3882 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003883 return rcode;
3884}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003885#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003886
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003887/* Start all the jobs, but don't wait for anything to finish.
3888 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003889 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003890 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003891 * to finish to determine the exit status of the pipe. If the pipe
3892 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003893 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003894 * return value.
3895 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003896 * Returns -1 only if started some children. IOW: we have to
3897 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003898 *
3899 * The only case when we do not need to [v]fork is when the pipe
3900 * is single, non-backgrounded, non-subshell command. Examples:
3901 * cmd ; ... { list } ; ...
3902 * cmd && ... { list } && ...
3903 * cmd || ... { list } || ...
3904 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3905 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003906 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003907 *
3908 * Cases when we must fork:
3909 * non-single: cmd | cmd
3910 * backgrounded: cmd & { list } &
3911 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003912 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02003913static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003914{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003915 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003916 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003917 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003918 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003919 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003920 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003921 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003922 /* it is not always needed, but we aim to smaller code */
3923 int squirrel[] = { -1, -1, -1 };
3924 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003925
Denis Vlasenko552433b2009-04-04 19:29:21 +00003926 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003927 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003928
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003929 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003930 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003931 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003932 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003933
Denis Vlasenko552433b2009-04-04 19:29:21 +00003934 if (pi->num_cmds != 1
3935 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003936 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00003937 ) {
3938 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003939 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003940
Denis Vlasenko552433b2009-04-04 19:29:21 +00003941 pi->alive_cmds = 1;
3942
3943 debug_printf_exec(": group:%p argv:'%s'\n",
3944 command->group, command->argv ? command->argv[0] : "NONE");
3945
3946 if (command->group) {
3947#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003948 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003949 /* "executing" func () { list } */
3950 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003951
Denis Vlasenkobc569742009-04-12 20:35:19 +00003952 funcp = new_function(command->argv[0]);
3953 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003954 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003955# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003956 funcp->body_as_string = command->group_as_string;
3957 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003958# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003959 command->group = NULL;
3960 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003961 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3962 funcp->parent_cmd = command;
3963 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003964
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003965 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3966 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003967 return EXIT_SUCCESS;
3968 }
3969#endif
3970 /* { list } */
3971 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003972 rcode = 1; /* exitcode if redir failed */
3973 if (setup_redirects(command, squirrel) == 0) {
3974 debug_printf_exec(": run_list\n");
3975 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003976 }
Eric Andersen04407e52001-06-07 16:42:05 +00003977 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003978 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003979 debug_leave();
3980 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003981 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003982 }
3983
Denis Vlasenko552433b2009-04-04 19:29:21 +00003984 argv = command->argv ? command->argv : (char **) &null_ptr;
3985 {
3986 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003987#if ENABLE_HUSH_FUNCTIONS
3988 const struct function *funcp;
3989#else
3990 enum { funcp = 0 };
3991#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003992 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003993 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003994
Denis Vlasenko552433b2009-04-04 19:29:21 +00003995 if (argv[command->assignment_cnt] == NULL) {
3996 /* Assignments, but no command */
3997 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003998 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003999 restore_redirects(squirrel);
4000 /* Set shell variables */
4001 while (*argv) {
4002 p = expand_string_to_string(*argv);
4003 debug_printf_exec("set shell var:'%s'->'%s'\n",
4004 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02004005 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004006 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00004007 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00004008 /* Do we need to flag set_local_var() errors?
4009 * "assignment to readonly var" and "putenv error"
4010 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004011 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004012 debug_leave();
4013 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004014 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00004015 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004016
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004017 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004018 if (0) {}
4019#if ENABLE_HUSH_BASH_COMPAT
4020 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004021 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
4022 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004023#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004024#ifdef CMD_SINGLEWORD_NOGLOB_COND
4025 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
4026 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
4027
4028 }
4029#endif
4030 else {
4031 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
4032 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004033
Denys Vlasenkof37eb392009-10-18 11:46:35 +02004034 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04004035 if (!argv_expanded[0]) {
4036 debug_leave();
Denys Vlasenko00243b02009-11-16 02:00:03 +01004037 return G.last_exitcode;
Mike Frysinger28736c32009-10-18 01:11:45 -04004038 }
4039
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004040 x = find_builtin(argv_expanded[0]);
4041#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004042 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004043 if (!x)
4044 funcp = find_function(argv_expanded[0]);
4045#endif
4046 if (x || funcp) {
4047 if (!funcp) {
4048 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
4049 debug_printf("exec with redirects only\n");
4050 rcode = setup_redirects(command, NULL);
4051 goto clean_up_and_ret1;
4052 }
Eric Andersen25f27032001-04-26 23:22:31 +00004053 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004054 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004055 * This is perfect for work that comes after exec().
4056 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00004057 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004058 rcode = setup_redirects(command, squirrel);
4059 if (rcode == 0) {
4060 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004061 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004062 if (!funcp) {
4063 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004064 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004065 rcode = x->function(argv_expanded) & 0xff;
Denys Vlasenko8131eea2009-11-02 14:19:51 +01004066 fflush_all();
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004067 }
4068#if ENABLE_HUSH_FUNCTIONS
4069 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02004070# if ENABLE_HUSH_LOCAL
4071 struct variable **sv;
4072 sv = G.shadowed_vars_pp;
4073 G.shadowed_vars_pp = &old_vars;
4074# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004075 debug_printf_exec(": function '%s' '%s'...\n",
4076 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00004077 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02004078# if ENABLE_HUSH_LOCAL
4079 G.shadowed_vars_pp = sv;
4080# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004081 }
4082#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004083 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004084#if ENABLE_FEATURE_SH_STANDALONE
4085 clean_up_and_ret:
4086#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004087 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004088 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004089 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004090 clean_up_and_ret1:
4091 free(argv_expanded);
4092 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004093 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004094 debug_printf_exec("run_pipe return %d\n", rcode);
4095 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004096 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004097
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004098#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004099 i = find_applet_by_name(argv_expanded[0]);
4100 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004101 rcode = setup_redirects(command, squirrel);
4102 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004103 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004104 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004105 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004106 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004107 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004108 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004109 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004110 }
4111#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00004112 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00004113 }
4114
Denis Vlasenko552433b2009-04-04 19:29:21 +00004115 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004116 /* NB: argv_expanded may already be created, and that
4117 * might include `cmd` runs! Do not rerun it! We *must*
4118 * use argv_expanded if it's non-NULL */
4119
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004120 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004121 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004122 nextin = 0;
4123
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004124 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004125 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004126#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004127 volatile nommu_save_t nommu_save;
4128 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004129 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004130 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004131 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00004132#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004133 command = &(pi->cmds[i]);
4134 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004135 debug_printf_exec(": pipe member '%s' '%s'...\n",
4136 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004137 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004138 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004139 }
Eric Andersen25f27032001-04-26 23:22:31 +00004140
4141 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004142 pipefds.rd = 0;
4143 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004144 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004145 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004146
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004147 command->pid = BB_MMU ? fork() : vfork();
4148 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004149#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004150 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004151 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004152
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004153 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004154 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004155 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004156 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004157 pgrp = pi->pgrp;
4158 if (pgrp < 0) /* true for 1st process only */
4159 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004160 if (setpgid(0, pgrp) == 0
4161 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004162 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004163 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004164 /* We do it in *every* child, not just first,
4165 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004166 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004167 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004168 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004169#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004170 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4171 /* 1st cmd in backgrounded pipe
4172 * should have its stdin /dev/null'ed */
4173 close(0);
4174 if (open(bb_dev_null, O_RDONLY))
4175 xopen("/", O_RDONLY);
4176 } else {
4177 xmove_fd(nextin, 0);
4178 }
4179 xmove_fd(pipefds.wr, 1);
4180 if (pipefds.rd > 1)
4181 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004182 /* Like bash, explicit redirects override pipes,
4183 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004184 if (setup_redirects(command, NULL))
4185 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004186
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004187 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004188 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4189
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004190 /* Stores to nommu_save list of env vars putenv'ed
4191 * (NOMMU, on MMU we don't need that) */
4192 /* cast away volatility... */
4193 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004194 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004195 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004196
Denis Vlasenkof9375282009-04-05 19:13:39 +00004197 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004198#if ENABLE_HUSH_FAST
4199 G.count_SIGCHLD++;
4200//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4201#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004202 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004203#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004204 /* Clean up after vforked child */
4205 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004206 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004207 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004208 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004209#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004210 free(argv_expanded);
4211 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004212 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004213 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004214 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004215 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004216 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004217#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004218 /* Second and next children need to know pid of first one */
4219 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004220 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004221#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004222 }
Eric Andersen25f27032001-04-26 23:22:31 +00004223
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004224 if (i)
4225 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004226 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004227 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004228 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004229 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004230 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004231
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004232 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004233 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004234 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4235 return 1;
4236 }
4237
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004238 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004239 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004240 return -1;
4241}
4242
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004243#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004244static void debug_print_tree(struct pipe *pi, int lvl)
4245{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004246 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004247 [PIPE_SEQ] = "SEQ",
4248 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004249 [PIPE_OR ] = "OR" ,
4250 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004251 };
4252 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004253 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004254# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004255 [RES_IF ] = "IF" ,
4256 [RES_THEN ] = "THEN" ,
4257 [RES_ELIF ] = "ELIF" ,
4258 [RES_ELSE ] = "ELSE" ,
4259 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004260# endif
4261# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004262 [RES_FOR ] = "FOR" ,
4263 [RES_WHILE] = "WHILE",
4264 [RES_UNTIL] = "UNTIL",
4265 [RES_DO ] = "DO" ,
4266 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004267# endif
4268# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004269 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004270# endif
4271# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004272 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004273 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004274 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004275 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004276 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004277# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004278 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004279 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004280 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004281 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004282 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004283 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004284 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004285# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004286 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004287# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004288 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004289
4290 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004291
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004292 pin = 0;
4293 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004294 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4295 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004296 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004297 while (prn < pi->num_cmds) {
4298 struct command *command = &pi->cmds[prn];
4299 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004300
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004301 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004302 lvl*2, "", prn,
4303 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004304 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004305 fprintf(stderr, " group %s: (argv=%p)\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004306 CMDTYPE[command->cmd_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004307 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004308 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004309 prn++;
4310 continue;
4311 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004312 if (argv) while (*argv) {
4313 fprintf(stderr, " '%s'", *argv);
4314 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004315 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004316 fprintf(stderr, "\n");
4317 prn++;
4318 }
4319 pi = pi->next;
4320 pin++;
4321 }
4322}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004323#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004324
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004325/* NB: called by pseudo_exec, and therefore must not modify any
4326 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004327static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004328{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004329#if ENABLE_HUSH_CASE
4330 char *case_word = NULL;
4331#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004332#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004333 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004334 char **for_lcur = NULL;
4335 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004336#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004337 smallint last_followup;
4338 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004339#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004340 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004341#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004342 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004343#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004344#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004345 smallint rword; /* enum reserved_style */
4346 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004347#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004348
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004349 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004350 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004351
Denis Vlasenko06810332007-05-21 23:30:54 +00004352#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004353 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004354 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4355 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004356 continue;
4357 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004358 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004359 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004360 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004361 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004362 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004363 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004364 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004365 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004366 continue;
4367 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004368 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4369 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004370 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004371 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004372 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004373 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004374 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004375 }
4376 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004377#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004378
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004379 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004380 * in order to return, no direct "return" statements please.
4381 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004382
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004383#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004384 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004385#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004386
Denis Vlasenko0e151382009-04-06 18:40:31 +00004387#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004388 rword = RES_NONE;
4389 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004390#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004391 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004392 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004393
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004394 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004395 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004396 if (G.flag_SIGINT)
4397 break;
4398
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004399 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004400 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4401 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004402#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004403 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004404 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004405 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004406 /* start of a loop: remember where loop starts */
4407 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004408 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004409 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004410#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004411 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004412 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004413 if ((rcode == 0 && last_followup == PIPE_OR)
4414 || (rcode != 0 && last_followup == PIPE_AND)
4415 ) {
4416 /* It is "<true> || CMD" or "<false> && CMD"
4417 * and we should not execute CMD */
4418 debug_printf_exec("skipped cmd because of || or &&\n");
4419 last_followup = pi->followup;
4420 continue;
4421 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004422 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004423 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004424 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004425#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004426 if (cond_code) {
4427 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004428 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004429 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004430 /* "if <false> THEN cmd": skip cmd */
4431 continue;
4432 }
4433 } else {
4434 if (rword == RES_ELSE || rword == RES_ELIF) {
4435 /* "if <true> then ... ELSE/ELIF cmd":
4436 * skip cmd and all following ones */
4437 break;
4438 }
4439 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004440#endif
4441#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004442 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004443 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004444 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004445
4446 static const char encoded_dollar_at[] ALIGN1 = {
4447 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4448 }; /* encoded representation of "$@" */
4449 static const char *const encoded_dollar_at_argv[] = {
4450 encoded_dollar_at, NULL
4451 }; /* argv list with one element: "$@" */
4452 char **vals;
4453
4454 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004455 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004456 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004457 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004458 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004459 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004460 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004461 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004462 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004463 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004464 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004465 debug_print_strings("for_list made from", vals);
4466 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004467 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004468 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004469 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004470 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004471 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004472 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004473 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004474 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004475 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004476 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004477 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004478 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004479 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 +02004480 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004481 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004482 if (rword == RES_IN) {
4483 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4484 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004485 if (rword == RES_DONE) {
4486 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004487 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004488#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004489#if ENABLE_HUSH_CASE
4490 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004491 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004492 continue;
4493 }
4494 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004495 char **argv;
4496
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004497 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4498 break;
4499 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004500 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004501 while (*argv) {
4502 char *pattern = expand_string_to_string(*argv);
4503 /* TODO: which FNM_xxx flags to use? */
4504 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4505 free(pattern);
4506 if (cond_code == 0) { /* match! we will execute this branch */
4507 free(case_word); /* make future "word)" stop */
4508 case_word = NULL;
4509 break;
4510 }
4511 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004512 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004513 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004514 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004515 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004516 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004517 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004518 }
4519#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004520 /* Just pressing <enter> in shell should check for jobs.
4521 * OTOH, in non-interactive shell this is useless
4522 * and only leads to extra job checks */
4523 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004524 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004525 goto check_jobs_and_continue;
4526 continue;
4527 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004528
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004529 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004530 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004531 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004532 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004533 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004534 {
4535 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004536#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004537 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004538#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004539 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4540 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004541 /* We ran a builtin, function, or group.
4542 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004543 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004544 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004545 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004546 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004547#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004548 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004549 if (G.flag_break_continue) {
4550 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004551 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004552 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004553 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004554 G.depth_break_continue--;
4555 if (G.depth_break_continue == 0)
4556 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004557 /* else: e.g. "continue 2" should *break* once, *then* continue */
4558 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004559 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004560 goto check_jobs_and_break;
4561 /* "continue": simulate end of loop */
4562 rword = RES_DONE;
4563 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004564 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004565#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004566#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004567 if (G.flag_return_in_progress == 1) {
4568 /* same as "goto check_jobs_and_break" */
4569 checkjobs(NULL);
4570 break;
4571 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004572#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004573 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004574 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004575 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004576 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4577 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004578 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004579#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004580 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004581 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004582#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004583 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004584 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004585 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004586#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004587 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004588 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004589 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004590 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004591 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004592 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004593#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004594 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004595 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004596 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004597 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004598 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004599 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004600 }
4601 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004602
4603 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004604#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004605 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004606 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004607#endif
4608#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004609 /* Beware of "while false; true; do ..."! */
4610 if (pi->next && pi->next->res_word == RES_DO) {
4611 if (rword == RES_WHILE) {
4612 if (rcode) {
4613 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004614 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004615 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4616 goto check_jobs_and_break;
4617 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004618 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004619 if (rword == RES_UNTIL) {
4620 if (!rcode) {
4621 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004622 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004623 checkjobs(NULL);
4624 break;
4625 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004626 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004627 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004628#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004629
4630 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004631 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004632 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004633
4634#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004635 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004636#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004637#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004638 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004639 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004640 free(for_list);
4641#endif
4642#if ENABLE_HUSH_CASE
4643 free(case_word);
4644#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004645 debug_leave();
4646 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004647 return rcode;
4648}
4649
Eric Andersen25f27032001-04-26 23:22:31 +00004650/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004651static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004652{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004653 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004654 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004655 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004656 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004657 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004658 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004659 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004660 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004661 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004662 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004663 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004664 return rcode;
4665}
4666
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004667
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004668static struct pipe *new_pipe(void)
4669{
Eric Andersen25f27032001-04-26 23:22:31 +00004670 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004671 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004672 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004673 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004674 return pi;
4675}
4676
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004677/* Command (member of a pipe) is complete, or we start a new pipe
4678 * if ctx->command is NULL.
4679 * No errors possible here.
4680 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004681static int done_command(struct parse_context *ctx)
4682{
4683 /* The command is really already in the pipe structure, so
4684 * advance the pipe counter and make a new, null command. */
4685 struct pipe *pi = ctx->pipe;
4686 struct command *command = ctx->command;
4687
4688 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004689 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004690 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004691 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004692 }
4693 pi->num_cmds++;
4694 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004695 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004696 } else {
4697 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4698 }
4699
4700 /* Only real trickiness here is that the uncommitted
4701 * command structure is not counted in pi->num_cmds. */
4702 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004703 ctx->command = command = &pi->cmds[pi->num_cmds];
4704 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004705 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004706 return pi->num_cmds; /* used only for 0/nonzero check */
4707}
4708
4709static void done_pipe(struct parse_context *ctx, pipe_style type)
4710{
4711 int not_null;
4712
4713 debug_printf_parse("done_pipe entered, followup %d\n", type);
4714 /* Close previous command */
4715 not_null = done_command(ctx);
4716 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004717#if HAS_KEYWORDS
4718 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4719 ctx->ctx_inverted = 0;
4720 ctx->pipe->res_word = ctx->ctx_res_w;
4721#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004722
4723 /* Without this check, even just <enter> on command line generates
4724 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004725 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004726 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004727#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004728 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004729#endif
4730#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004731 || ctx->ctx_res_w == RES_DONE
4732 || ctx->ctx_res_w == RES_FOR
4733 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004734#endif
4735#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004736 || ctx->ctx_res_w == RES_ESAC
4737#endif
4738 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004739 struct pipe *new_p;
4740 debug_printf_parse("done_pipe: adding new pipe: "
4741 "not_null:%d ctx->ctx_res_w:%d\n",
4742 not_null, ctx->ctx_res_w);
4743 new_p = new_pipe();
4744 ctx->pipe->next = new_p;
4745 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004746 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004747 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004748 * This is used to control execution.
4749 * RES_FOR and RES_IN are NOT sticky (needed to support
4750 * cases where variable or value happens to match a keyword):
4751 */
4752#if ENABLE_HUSH_LOOPS
4753 if (ctx->ctx_res_w == RES_FOR
4754 || ctx->ctx_res_w == RES_IN)
4755 ctx->ctx_res_w = RES_NONE;
4756#endif
4757#if ENABLE_HUSH_CASE
4758 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004759 ctx->ctx_res_w = RES_CASE_BODY;
4760 if (ctx->ctx_res_w == RES_CASE)
4761 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004762#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004763 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004764 /* Create the memory for command, roughly:
4765 * ctx->pipe->cmds = new struct command;
4766 * ctx->command = &ctx->pipe->cmds[0];
4767 */
4768 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004769 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004770 }
4771 debug_printf_parse("done_pipe return\n");
4772}
4773
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004774static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004775{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004776 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004777 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004778 /* Create the memory for command, roughly:
4779 * ctx->pipe->cmds = new struct command;
4780 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004781 */
4782 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004783}
4784
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004785/* If a reserved word is found and processed, parse context is modified
4786 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004787 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004788#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004789struct reserved_combo {
4790 char literal[6];
4791 unsigned char res;
4792 unsigned char assignment_flag;
4793 int flag;
4794};
4795enum {
4796 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004797# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004798 FLAG_IF = (1 << RES_IF ),
4799 FLAG_THEN = (1 << RES_THEN ),
4800 FLAG_ELIF = (1 << RES_ELIF ),
4801 FLAG_ELSE = (1 << RES_ELSE ),
4802 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004803# endif
4804# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004805 FLAG_FOR = (1 << RES_FOR ),
4806 FLAG_WHILE = (1 << RES_WHILE),
4807 FLAG_UNTIL = (1 << RES_UNTIL),
4808 FLAG_DO = (1 << RES_DO ),
4809 FLAG_DONE = (1 << RES_DONE ),
4810 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004811# endif
4812# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004813 FLAG_MATCH = (1 << RES_MATCH),
4814 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004815# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004816 FLAG_START = (1 << RES_XXXX ),
4817};
4818
4819static const struct reserved_combo* match_reserved_word(o_string *word)
4820{
Eric Andersen25f27032001-04-26 23:22:31 +00004821 /* Mostly a list of accepted follow-up reserved words.
4822 * FLAG_END means we are done with the sequence, and are ready
4823 * to turn the compound list into a command.
4824 * FLAG_START means the word must start a new compound list.
4825 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004826 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004827# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004828 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4829 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4830 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4831 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4832 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4833 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004834# endif
4835# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004836 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4837 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4838 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4839 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4840 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4841 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004842# endif
4843# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004844 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4845 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004846# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004847 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004848 const struct reserved_combo *r;
4849
4850 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4851 if (strcmp(word->data, r->literal) == 0)
4852 return r;
4853 }
4854 return NULL;
4855}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004856/* Return 0: not a keyword, 1: keyword
4857 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004858static int reserved_word(o_string *word, struct parse_context *ctx)
4859{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004860# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004861 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004862 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004863 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004864# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004865 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004866
Denis Vlasenkobb929512009-04-16 10:59:40 +00004867 if (word->o_quoted)
4868 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004869 r = match_reserved_word(word);
4870 if (!r)
4871 return 0;
4872
4873 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004874# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004875 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4876 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004877 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004878 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004879# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004880 if (r->flag == 0) { /* '!' */
4881 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004882 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004883 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004884 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004885 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004886 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004887 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004888 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004889 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004890
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004891 old = xmalloc(sizeof(*old));
4892 debug_printf_parse("push stack %p\n", old);
4893 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004894 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004895 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004896 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004897 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004898 ctx->ctx_res_w = RES_SNTX;
4899 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004900 } else {
4901 /* "{...} fi" is ok. "{...} if" is not
4902 * Example:
4903 * if { echo foo; } then { echo bar; } fi */
4904 if (ctx->command->group)
4905 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004906 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004907
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004908 ctx->ctx_res_w = r->res;
4909 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004910 word->o_assignment = r->assignment_flag;
4911
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004912 if (ctx->old_flag & FLAG_END) {
4913 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004914
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004915 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004916 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004917 old = ctx->stack;
4918 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004919 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004920# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004921 o_addstr(&old->as_string, ctx->as_string.data);
4922 o_free_unsafe(&ctx->as_string);
4923 old->command->group_as_string = xstrdup(old->as_string.data);
4924 debug_printf_parse("pop, remembering as:'%s'\n",
4925 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004926# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004927 *ctx = *old; /* physical copy */
4928 free(old);
4929 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004930 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004931}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004932#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004933
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004934/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004935 * Normal return is 0. Syntax errors return 1.
4936 * Note: on return, word is reset, but not o_free'd!
4937 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004938static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004939{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004940 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004941
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004942 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004943 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004944 debug_printf_parse("done_word return 0: true null, ignored\n");
4945 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004946 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004947
Eric Andersen25f27032001-04-26 23:22:31 +00004948 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004949 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4950 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004951 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4952 * "2.7 Redirection
4953 * ...the word that follows the redirection operator
4954 * shall be subjected to tilde expansion, parameter expansion,
4955 * command substitution, arithmetic expansion, and quote
4956 * removal. Pathname expansion shall not be performed
4957 * on the word by a non-interactive shell; an interactive
4958 * shell may perform it, but shall do so only when
4959 * the expansion would result in one word."
4960 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004961 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004962 /* Cater for >\file case:
4963 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4964 * Same with heredocs:
4965 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4966 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004967 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4968 unbackslash(ctx->pending_redirect->rd_filename);
4969 /* Is it <<"HEREDOC"? */
4970 if (word->o_quoted) {
4971 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4972 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004973 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004974 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004975 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004976 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004977 /* If this word wasn't an assignment, next ones definitely
4978 * can't be assignments. Even if they look like ones. */
4979 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4980 && word->o_assignment != WORD_IS_KEYWORD
4981 ) {
4982 word->o_assignment = NOT_ASSIGNMENT;
4983 } else {
4984 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4985 command->assignment_cnt++;
4986 word->o_assignment = MAYBE_ASSIGNMENT;
4987 }
4988
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004989#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004990# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004991 if (ctx->ctx_dsemicolon
4992 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4993 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004994 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004995 /* ctx->ctx_res_w = RES_MATCH; */
4996 ctx->ctx_dsemicolon = 0;
4997 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004998# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004999 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005000# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005001 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
5002 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005003# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005004# if ENABLE_HUSH_CASE
5005 && ctx->ctx_res_w != RES_CASE
5006# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005007 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005008 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00005009 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005010 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005011 debug_printf_parse("done_word return %d\n",
5012 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005013 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005014 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005015# ifdef CMD_SINGLEWORD_NOGLOB_COND
5016 if (strcmp(word->data, "export") == 0
5017# if ENABLE_HUSH_LOCAL
5018 || strcmp(word->data, "local") == 0
5019# endif
5020 ) {
5021 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
5022 } else
5023# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005024# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005025 if (strcmp(word->data, "[[") == 0) {
5026 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
5027 }
5028 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02005029# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005030 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005031#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00005032 if (command->group) {
5033 /* "{ echo foo; } echo bar" - bad */
5034 syntax_error_at(word->data);
5035 debug_printf_parse("done_word return 1: syntax error, "
5036 "groups and arglists don't mix\n");
5037 return 1;
5038 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005039 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00005040 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
5041 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005042 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00005043 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005044 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005045 char *p = word->data;
5046 while (p[0] == SPECIAL_VAR_SYMBOL
5047 && (p[1] & 0x7f) == '@'
5048 && p[2] == SPECIAL_VAR_SYMBOL
5049 ) {
5050 p += 3;
5051 }
5052 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005053 /* saw no "$@", or not only "$@" but some
5054 * real text is there too */
5055 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00005056 * e.g. "", $empty"" etc to not disappear */
5057 o_addchr(word, SPECIAL_VAR_SYMBOL);
5058 o_addchr(word, SPECIAL_VAR_SYMBOL);
5059 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00005060 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005061 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005062 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005063 }
Eric Andersen25f27032001-04-26 23:22:31 +00005064
Denis Vlasenko06810332007-05-21 23:30:54 +00005065#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005066 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005067 if (word->o_quoted
5068 || !is_well_formed_var_name(command->argv[0], '\0')
5069 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005070 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005071 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005072 return 1;
5073 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005074 /* Force FOR to have just one word (variable name) */
5075 /* NB: basically, this makes hush see "for v in ..."
5076 * syntax as if it is "for v; in ...". FOR and IN become
5077 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005078 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00005079 }
Denis Vlasenko06810332007-05-21 23:30:54 +00005080#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005081#if ENABLE_HUSH_CASE
5082 /* Force CASE to have just one word */
5083 if (ctx->ctx_res_w == RES_CASE) {
5084 done_pipe(ctx, PIPE_SEQ);
5085 }
5086#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005087
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005088 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00005089
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005090 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005091 return 0;
5092}
5093
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005094
5095/* Peek ahead in the input to find out if we have a "&n" construct,
5096 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005097 * Return:
5098 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
5099 * REDIRFD_SYNTAX_ERR if syntax error,
5100 * REDIRFD_TO_FILE if no & was seen,
5101 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005102 */
5103#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005104#define parse_redir_right_fd(as_string, input) \
5105 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005106#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005107static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005108{
5109 int ch, d, ok;
5110
5111 ch = i_peek(input);
5112 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005113 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005114
5115 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005116 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005117 ch = i_peek(input);
5118 if (ch == '-') {
5119 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005120 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005121 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005122 }
5123 d = 0;
5124 ok = 0;
5125 while (ch != EOF && isdigit(ch)) {
5126 d = d*10 + (ch-'0');
5127 ok = 1;
5128 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005129 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005130 ch = i_peek(input);
5131 }
5132 if (ok) return d;
5133
5134//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
5135
5136 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005137 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005138}
5139
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005140/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005141 */
5142static int parse_redirect(struct parse_context *ctx,
5143 int fd,
5144 redir_type style,
5145 struct in_str *input)
5146{
5147 struct command *command = ctx->command;
5148 struct redir_struct *redir;
5149 struct redir_struct **redirp;
5150 int dup_num;
5151
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005152 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005153 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005154 /* Check for a '>&1' type redirect */
5155 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5156 if (dup_num == REDIRFD_SYNTAX_ERR)
5157 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005158 } else {
5159 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005160 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005161 if (dup_num) { /* <<-... */
5162 ch = i_getch(input);
5163 nommu_addchr(&ctx->as_string, ch);
5164 ch = i_peek(input);
5165 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005166 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005167
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005168 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005169 int ch = i_peek(input);
5170 if (ch == '|') {
5171 /* >|FILE redirect ("clobbering" >).
5172 * Since we do not support "set -o noclobber" yet,
5173 * >| and > are the same for now. Just eat |.
5174 */
5175 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005176 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005177 }
5178 }
5179
5180 /* Create a new redir_struct and append it to the linked list */
5181 redirp = &command->redirects;
5182 while ((redir = *redirp) != NULL) {
5183 redirp = &(redir->next);
5184 }
5185 *redirp = redir = xzalloc(sizeof(*redir));
5186 /* redir->next = NULL; */
5187 /* redir->rd_filename = NULL; */
5188 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005189 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005190
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005191 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5192 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005193
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005194 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005195 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005196 /* Erik had a check here that the file descriptor in question
5197 * is legit; I postpone that to "run time"
5198 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005199 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5200 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005201 } else {
5202 /* Set ctx->pending_redirect, so we know what to do at the
5203 * end of the next parsed word. */
5204 ctx->pending_redirect = redir;
5205 }
5206 return 0;
5207}
5208
Eric Andersen25f27032001-04-26 23:22:31 +00005209/* If a redirect is immediately preceded by a number, that number is
5210 * supposed to tell which file descriptor to redirect. This routine
5211 * looks for such preceding numbers. In an ideal world this routine
5212 * needs to handle all the following classes of redirects...
5213 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5214 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5215 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5216 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005217 *
5218 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5219 * "2.7 Redirection
5220 * ... If n is quoted, the number shall not be recognized as part of
5221 * the redirection expression. For example:
5222 * echo \2>a
5223 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005224 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005225 *
5226 * A -1 return means no valid number was found,
5227 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005228 */
5229static int redirect_opt_num(o_string *o)
5230{
5231 int num;
5232
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005233 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005234 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005235 num = bb_strtou(o->data, NULL, 10);
5236 if (errno || num < 0)
5237 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005238 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005239 return num;
5240}
5241
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005242#if BB_MMU
5243#define fetch_till_str(as_string, input, word, skip_tabs) \
5244 fetch_till_str(input, word, skip_tabs)
5245#endif
5246static char *fetch_till_str(o_string *as_string,
5247 struct in_str *input,
5248 const char *word,
5249 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005250{
5251 o_string heredoc = NULL_O_STRING;
5252 int past_EOL = 0;
5253 int ch;
5254
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005255 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005256 while (1) {
5257 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005258 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005259 if (ch == '\n') {
5260 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5261 heredoc.data[past_EOL] = '\0';
5262 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5263 return heredoc.data;
5264 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005265 do {
5266 o_addchr(&heredoc, ch);
5267 past_EOL = heredoc.length;
5268 jump_in:
5269 do {
5270 ch = i_getch(input);
5271 nommu_addchr(as_string, ch);
5272 } while (skip_tabs && ch == '\t');
5273 } while (ch == '\n');
5274 }
5275 if (ch == EOF) {
5276 o_free_unsafe(&heredoc);
5277 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005278 }
5279 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005280 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005281 }
5282}
5283
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005284/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5285 * and load them all. There should be exactly heredoc_cnt of them.
5286 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005287static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5288{
5289 struct pipe *pi = ctx->list_head;
5290
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005291 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005292 int i;
5293 struct command *cmd = pi->cmds;
5294
5295 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5296 pi->num_cmds,
5297 cmd->argv ? cmd->argv[0] : "NONE");
5298 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005299 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005300
5301 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5302 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005303 while (redir) {
5304 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005305 char *p;
5306
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005307 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005308 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005309 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005310 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005311 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005312 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005313 return 1;
5314 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005315 free(redir->rd_filename);
5316 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005317 heredoc_cnt--;
5318 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005319 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005320 }
5321 cmd++;
5322 }
5323 pi = pi->next;
5324 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005325#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005326 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005327 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005328 bb_error_msg_and_die("heredoc BUG 2");
5329#endif
5330 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005331}
5332
5333
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005334#if ENABLE_HUSH_TICK
Denys Vlasenko647553a2009-11-15 19:58:19 +01005335static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
Eric Andersen25f27032001-04-26 23:22:31 +00005336{
Denys Vlasenko647553a2009-11-15 19:58:19 +01005337 pid_t pid;
5338 int channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005339# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005340 char **to_free;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005341# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005342
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005343 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005344 pid = BB_MMU ? fork() : vfork();
5345 if (pid < 0)
5346 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005347
Denis Vlasenko05743d72008-02-10 12:10:08 +00005348 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005349 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005350 /* Process substitution is not considered to be usual
5351 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005352 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5353 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005354 bb_signals(0
5355 + (1 << SIGTSTP)
5356 + (1 << SIGTTIN)
5357 + (1 << SIGTTOU)
5358 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005359 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005360 close(channel[0]); /* NB: close _first_, then move fd! */
5361 xmove_fd(channel[1], 1);
5362 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005363 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005364 /* Awful hack for `trap` or $(trap).
5365 *
5366 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5367 * contains an example where "trap" is executed in a subshell:
5368 *
5369 * save_traps=$(trap)
5370 * ...
5371 * eval "$save_traps"
5372 *
5373 * Standard does not say that "trap" in subshell shall print
5374 * parent shell's traps. It only says that its output
5375 * must have suitable form, but then, in the above example
5376 * (which is not supposed to be normative), it implies that.
5377 *
5378 * bash (and probably other shell) does implement it
5379 * (traps are reset to defaults, but "trap" still shows them),
5380 * but as a result, "trap" logic is hopelessly messed up:
5381 *
5382 * # trap
5383 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5384 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5385 * # true | trap <--- trap is in subshell - no output (ditto)
5386 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5387 * trap -- 'echo Ho' SIGWINCH
5388 * # echo `(trap)` <--- in subshell in subshell - output
5389 * trap -- 'echo Ho' SIGWINCH
5390 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5391 * trap -- 'echo Ho' SIGWINCH
5392 *
5393 * The rules when to forget and when to not forget traps
5394 * get really complex and nonsensical.
5395 *
5396 * Our solution: ONLY bare $(trap) or `trap` is special.
5397 */
5398 s = skip_whitespace(s);
5399 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5400 {
5401 static const char *const argv[] = { NULL, NULL };
5402 builtin_trap((char**)argv);
5403 exit(0); /* not _exit() - we need to fflush */
5404 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005405# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005406 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005407 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005408 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005409# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005410 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005411 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5412 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005413 * echo OK
5414 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005415 re_execute_shell(&to_free,
5416 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005417 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005418 G.global_argv + 1,
5419 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005420# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005421 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005422
5423 /* parent */
Denys Vlasenko647553a2009-11-15 19:58:19 +01005424 *pid_p = pid;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005425# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005426 G.count_SIGCHLD++;
5427//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 +02005428# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005429 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005430# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005431 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005432# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005433 close(channel[1]);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005434 close_on_exec_on(channel[0]);
5435 return xfdopen_for_read(channel[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00005436}
5437
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005438/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005439static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005440{
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005441 FILE *fp;
Eric Andersen25f27032001-04-26 23:22:31 +00005442 struct in_str pipe_str;
Denys Vlasenko647553a2009-11-15 19:58:19 +01005443 pid_t pid;
5444 int status, ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005445
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005446 fp = generate_stream_from_string(s, &pid);
Eric Andersen25f27032001-04-26 23:22:31 +00005447
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005448 /* Now send results of command back into original context */
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005449 setup_file_in_str(&pipe_str, fp);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005450 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005451 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005452 if (ch == '\n') {
5453 eol_cnt++;
5454 continue;
5455 }
5456 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005457 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005458 eol_cnt--;
5459 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005460 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005461 }
5462
Denys Vlasenko647553a2009-11-15 19:58:19 +01005463 debug_printf("done reading from `cmd` pipe, closing it\n");
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +01005464 fclose(fp);
Denys Vlasenko647553a2009-11-15 19:58:19 +01005465 /* We need to extract exitcode. Test case
5466 * "true; echo `sleep 1; false` $?"
5467 * should print 1 */
5468 safe_waitpid(pid, &status, 0);
5469 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5470 return WEXITSTATUS(status);
Eric Andersen25f27032001-04-26 23:22:31 +00005471}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005472#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005473
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005474static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005475 struct in_str *input, int ch)
5476{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005477 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005478 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005479 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005480 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005481 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005482 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005483
5484 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005485#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005486 if (ch == '(' && !dest->o_quoted) {
5487 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005488 if (done_word(dest, ctx))
5489 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005490 if (!command->argv)
5491 goto skip; /* (... */
5492 if (command->argv[1]) { /* word word ... (... */
5493 syntax_error_unexpected_ch('(');
5494 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005495 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005496 /* it is "word(..." or "word (..." */
5497 do
5498 ch = i_getch(input);
5499 while (ch == ' ' || ch == '\t');
5500 if (ch != ')') {
5501 syntax_error_unexpected_ch(ch);
5502 return 1;
5503 }
5504 nommu_addchr(&ctx->as_string, ch);
5505 do
5506 ch = i_getch(input);
5507 while (ch == ' ' || ch == '\t' || ch == '\n');
5508 if (ch != '{') {
5509 syntax_error_unexpected_ch(ch);
5510 return 1;
5511 }
5512 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005513 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005514 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005515 }
5516#endif
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005517
5518#if 0 /* Prevented by caller */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005519 if (command->argv /* word [word]{... */
5520 || dest->length /* word{... */
5521 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005522 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005523 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005524 debug_printf_parse("parse_group return 1: "
5525 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005526 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005527 }
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01005528#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005529
5530#if ENABLE_HUSH_FUNCTIONS
5531 skip:
5532#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005533 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005534 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005535 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005536 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005537 } else {
5538 /* bash does not allow "{echo...", requires whitespace */
5539 ch = i_getch(input);
5540 if (ch != ' ' && ch != '\t' && ch != '\n') {
5541 syntax_error_unexpected_ch(ch);
5542 return 1;
5543 }
5544 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005545 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005546
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005547 {
5548#if !BB_MMU
5549 char *as_string = NULL;
5550#endif
5551 pipe_list = parse_stream(&as_string, input, endch);
5552#if !BB_MMU
5553 if (as_string)
5554 o_addstr(&ctx->as_string, as_string);
5555#endif
5556 /* empty ()/{} or parse error? */
5557 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005558 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005559#if !BB_MMU
5560 free(as_string);
5561#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005562 debug_printf_parse("parse_group return 1: "
5563 "parse_stream returned %p\n", pipe_list);
5564 return 1;
5565 }
5566 command->group = pipe_list;
5567#if !BB_MMU
5568 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5569 command->group_as_string = as_string;
5570 debug_printf_parse("end of group, remembering as:'%s'\n",
5571 command->group_as_string);
5572#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005573 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005574 debug_printf_parse("parse_group return 0\n");
5575 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005576 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005577}
5578
Mike Frysinger98c52642009-04-02 10:02:37 +00005579#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005580/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005581static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005582/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005583static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005584{
5585 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005586 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005587 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005588 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005589 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005590 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005591 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005592 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005593 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005594 }
5595}
5596/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005597static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005598{
5599 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005600 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005601 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005602 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005603 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005604 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005605 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005606 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005607 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005608 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005609 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005610 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005611 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005612 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005613 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005614 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005615 continue;
5616 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005617 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005618 }
5619}
5620/* Process `cmd` - copy contents until "`" is seen. Complicated by
5621 * \` quoting.
5622 * "Within the backquoted style of command substitution, backslash
5623 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5624 * The search for the matching backquote shall be satisfied by the first
5625 * backquote found without a preceding backslash; during this search,
5626 * if a non-escaped backquote is encountered within a shell comment,
5627 * a here-document, an embedded command substitution of the $(command)
5628 * form, or a quoted string, undefined results occur. A single-quoted
5629 * or double-quoted string that begins, but does not end, within the
5630 * "`...`" sequence produces undefined results."
5631 * Example Output
5632 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5633 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005634static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005635{
5636 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005637 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005638 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005639 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005640 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005641 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005642 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005643 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005644 if (ch == '\\') {
5645 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005646 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005647 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005648 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005649 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005650 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005651 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005652 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005653 ch = ch2;
5654 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005655 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005656 }
5657}
5658/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5659 * quoting and nested ()s.
5660 * "With the $(command) style of command substitution, all characters
5661 * following the open parenthesis to the matching closing parenthesis
5662 * constitute the command. Any valid shell script can be used for command,
5663 * except a script consisting solely of redirections which produces
5664 * unspecified results."
5665 * Example Output
5666 * echo $(echo '(TEST)' BEST) (TEST) BEST
5667 * echo $(echo 'TEST)' BEST) TEST) BEST
5668 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5669 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005670static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005671{
5672 int count = 0;
5673 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005674 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005675 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005676 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005677 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005678 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005679 if (ch == '(')
5680 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005681 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005682 if (--count < 0) {
5683 if (!dbl)
5684 break;
5685 if (i_peek(input) == ')') {
5686 i_getch(input);
5687 break;
5688 }
5689 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005690 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005691 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005692 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005693 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005694 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005695 continue;
5696 }
5697 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005698 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005699 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005700 continue;
5701 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005702 if (ch == '\\') {
5703 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005704 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005705 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005706 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005707 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005708 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005709 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005710 continue;
5711 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005712 }
5713}
Mike Frysinger98c52642009-04-02 10:02:37 +00005714#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005715
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005716/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005717#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005718#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005719 handle_dollar(dest, input)
5720#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005721static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005722 o_string *dest,
5723 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005724{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005725 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005726 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005727
5728 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005729 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005730 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005731 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005732 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005733 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005734 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005735 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005736 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005737 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005738 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005739 if (!isalnum(ch) && ch != '_')
5740 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005741 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005742 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005743 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005744 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005745 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005746 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005747 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005748 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005749 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005750 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005751 o_addchr(dest, ch | quote_mask);
5752 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005753 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005754 case '$': /* pid */
5755 case '!': /* last bg pid */
5756 case '?': /* last exit code */
5757 case '#': /* number of args */
5758 case '*': /* args */
5759 case '@': /* args */
5760 goto make_one_char_var;
5761 case '{': {
5762 bool first_char, all_digits;
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005763 int expansion;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005764
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005765 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005766 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005767 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5768
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005769 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005770 expansion = 0;
5771 first_char = true;
5772 all_digits = false;
5773 while (1) {
5774 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005775 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005776 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005777 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005778 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005779
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005780 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005781 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005782 /* ${#var}: length of var contents */
5783 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005784 }
5785 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005786 all_digits = true;
5787 goto char_ok;
5788 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005789 /* They're being verbose and doing ${?} */
5790 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5791 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005792 }
5793
5794 if (expansion < 2
5795 && ( (all_digits && !isdigit(ch))
5796 || (!all_digits && !isalnum(ch) && ch != '_')
5797 )
5798 ) {
5799 /* handle parameter expansions
5800 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5801 */
5802 if (first_char)
5803 goto case_default;
5804 switch (ch) {
5805 case ':': /* null modifier */
5806 if (expansion == 0) {
5807 debug_printf_parse(": null modifier\n");
5808 ++expansion;
5809 break;
5810 }
5811 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005812 case '#': /* remove prefix */
5813 case '%': /* remove suffix */
5814 if (expansion == 0) {
5815 debug_printf_parse(": remove suffix/prefix\n");
5816 expansion = 2;
5817 break;
5818 }
5819 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005820 case '-': /* default value */
5821 case '=': /* assign default */
5822 case '+': /* alternative */
5823 case '?': /* error indicate */
5824 debug_printf_parse(": parameter expansion\n");
5825 expansion = 2;
5826 break;
5827 default:
5828 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005829 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005830 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5831 return 1;
5832 }
5833 }
5834 char_ok:
5835 debug_printf_parse(": '%c'\n", ch);
5836 o_addchr(dest, ch | quote_mask);
5837 quote_mask = 0;
5838 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005839 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005840 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5841 break;
5842 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005843#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005844 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005845# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005846 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005847# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005848 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005849 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005850# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005851 if (i_peek(input) == '(') {
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 Vlasenkoa24c8ca2009-04-04 15:24:40 +00005854 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5855 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005856# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005857 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005858# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005859 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005860# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005861 if (as_string) {
5862 o_addstr(as_string, dest->data + pos);
5863 o_addchr(as_string, ')');
5864 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005865 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005866# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005867 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005868 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005869 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005870# endif
5871# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005872 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5873 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005874# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005875 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005876# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005877 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005878# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005879 if (as_string) {
5880 o_addstr(as_string, dest->data + pos);
5881 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005882 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005883# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005885# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005886 break;
5887 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005888#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005889 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005890 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005891 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005892 ch = i_peek(input);
5893 if (isalnum(ch)) { /* it's $_name or $_123 */
5894 ch = '_';
5895 goto make_var;
5896 }
5897 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005898 /* TODO: $_ and $-: */
5899 /* $_ Shell or shell script name; or last argument of last command
5900 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5901 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005902 /* $- Option flags set by set builtin or shell options (-i etc) */
5903 default:
5904 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005905 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005906 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005907 return 0;
5908}
5909
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005910#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005911#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005912 parse_stream_dquoted(dest, input, dquote_end)
5913#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005914static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005915 o_string *dest,
5916 struct in_str *input,
5917 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005918{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005919 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005920 int next;
5921
5922 again:
5923 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005924 if (ch != EOF)
5925 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005926 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005927 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005928 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005929 debug_printf_parse("parse_stream_dquoted return 0\n");
5930 return 0;
5931 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005932 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005933 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005934 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005935 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005936 }
5937 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005938 if (ch != '\n') {
5939 next = i_peek(input);
5940 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005941 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005942 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005943 if (ch == '\\') {
5944 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005945 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005946 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005947 }
5948 /* bash:
5949 * "The backslash retains its special meaning [in "..."]
5950 * only when followed by one of the following characters:
5951 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005952 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005953 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005954 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005955 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005956 if (ch != '\n') {
5957 o_addqchr(dest, ch);
5958 nommu_addchr(as_string, ch);
5959 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005960 } else {
5961 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005962 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005963 }
5964 goto again;
5965 }
5966 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005967 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005968 debug_printf_parse("parse_stream_dquoted return 1: "
5969 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005970 return 1;
5971 }
5972 goto again;
5973 }
5974#if ENABLE_HUSH_TICK
5975 if (ch == '`') {
5976 //int pos = dest->length;
5977 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5978 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005979 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005980 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5981 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005982 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005983 }
5984#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005985 o_addQchr(dest, ch);
5986 if (ch == '='
5987 && (dest->o_assignment == MAYBE_ASSIGNMENT
5988 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005989 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005990 ) {
5991 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5992 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005993 goto again;
5994}
5995
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005996/*
5997 * Scan input until EOF or end_trigger char.
5998 * Return a list of pipes to execute, or NULL on EOF
5999 * or if end_trigger character is met.
6000 * On syntax error, exit is shell is not interactive,
6001 * reset parsing machinery and start parsing anew,
6002 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006003 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006004static struct pipe *parse_stream(char **pstring,
6005 struct in_str *input,
6006 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006007{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006008 struct parse_context ctx;
6009 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006010 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006011 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00006012
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00006013 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00006014 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006015 * found. When recursing, quote state is passed in via dest->o_escape.
6016 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006017 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02006018 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006019 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006020
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006021 /* If very first arg is "" or '', dest.data may end up NULL.
6022 * Preventing this: */
6023 o_addchr(&dest, '\0');
6024 dest.length = 0;
6025
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006026 G.ifs = get_local_var_value("IFS");
6027 if (G.ifs == NULL)
6028 G.ifs = " \t\n";
6029
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006030 reset:
6031#if ENABLE_HUSH_INTERACTIVE
6032 input->promptmode = 0; /* PS1 */
6033#endif
6034 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
6035 initialize_context(&ctx);
6036 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006037 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006038 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006039 const char *is_ifs;
6040 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006041 int ch;
6042 int next;
6043 int redir_fd;
6044 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006045
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006046 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006047 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006048 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006049 goto parse_error;
6050 }
6051 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006052 is_in_dquote = 0;
6053 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006054 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006055 debug_printf_parse(": ch=%c (%d) escape=%d\n",
6056 ch, ch, dest.o_escape);
6057 if (ch == EOF) {
6058 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006059
6060 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006061 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006062 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006063 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006064 /* end_trigger == '}' case errors out earlier,
6065 * checking only ')' */
6066 if (end_trigger == ')') {
6067 syntax_error_unterm_ch('('); /* exits */
6068 /* goto parse_error; */
6069 }
6070
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006071 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02006072 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006073 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006074 o_free(&dest);
6075 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006076 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006077 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006078 /* (this makes bare "&" cmd a no-op.
6079 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006080 if (pi->num_cmds == 0
6081 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
6082 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006083 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006084 pi = NULL;
6085 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006086#if !BB_MMU
6087 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6088 if (pstring)
6089 *pstring = ctx.as_string.data;
6090 else
6091 o_free_unsafe(&ctx.as_string);
6092#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006093 debug_leave();
6094 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006095 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00006096 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006097 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkod8389ad2009-11-16 03:18:46 +01006098
6099 next = '\0';
6100 if (ch != '\n')
6101 next = i_peek(input);
6102
6103 is_special = "{}<>;&|()#'" /* special outside of "str" */
6104 "\\$\"" IF_HUSH_TICK("`"); /* always special */
6105 /* Are { and } special here? */
6106 if (ctx.command->argv /* word [word]{... */
6107 || dest.length /* word{... */
6108 || dest.o_quoted /* ""{... */
6109 || (next != ';' && next != ')' && !strchr(G.ifs, next)) /* {word */
6110 ) {
6111 /* They are not special, skip "{}" */
6112 is_special += 2;
6113 }
6114 is_special = strchr(is_special, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006115 is_ifs = strchr(G.ifs, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006116
6117 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00006118 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006119 o_addQchr(&dest, ch);
6120 if ((dest.o_assignment == MAYBE_ASSIGNMENT
6121 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00006122 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006123 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00006124 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006125 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006126 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006127 continue;
6128 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00006129
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006130 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006131 if (done_word(&dest, &ctx)) {
6132 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00006133 }
Denis Vlasenko37181682009-04-03 03:19:15 +00006134 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00006135#if ENABLE_HUSH_CASE
6136 /* "case ... in <newline> word) ..." -
6137 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006138 if (ctx.command->argv == NULL
6139 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00006140 ) {
6141 continue;
6142 }
6143#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00006144 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006145 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006146 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
6147 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006148 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006149 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006150 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006151 heredoc_cnt = 0;
6152 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006153 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006154 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006155 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006156 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006157 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006158 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006159
6160 /* "cmd}" or "cmd }..." without semicolon or &:
6161 * } is an ordinary char in this case, even inside { cmd; }
6162 * Pathological example: { ""}; } should exec "}" cmd
6163 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006164 if (ch == '}') {
6165 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6166 || dest.length != 0 /* word} */
6167 || dest.o_quoted /* ""} */
6168 ) {
6169 goto ordinary_char;
6170 }
6171 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6172 goto skip_end_trigger;
6173 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006174 }
6175
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006176 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006177 && (ch != ';' || heredoc_cnt == 0)
6178#if ENABLE_HUSH_CASE
6179 && (ch != ')'
6180 || ctx.ctx_res_w != RES_MATCH
6181 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6182 )
6183#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006184 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006185 if (heredoc_cnt) {
6186 /* This is technically valid:
6187 * { cat <<HERE; }; echo Ok
6188 * heredoc
6189 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006190 * HERE
6191 * but we don't support this.
6192 * We require heredoc to be in enclosing {}/(),
6193 * if any.
6194 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006195 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006196 goto parse_error;
6197 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006198 if (done_word(&dest, &ctx)) {
6199 goto parse_error;
6200 }
6201 done_pipe(&ctx, PIPE_SEQ);
6202 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006203 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006204 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006205 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006206 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006207 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006208#if !BB_MMU
6209 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6210 if (pstring)
6211 *pstring = ctx.as_string.data;
6212 else
6213 o_free_unsafe(&ctx.as_string);
6214#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006215 debug_leave();
6216 debug_printf_parse("parse_stream return %p: "
6217 "end_trigger char found\n",
6218 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006219 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006220 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006221 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006222 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006223 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006224 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006225
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006226 /* Catch <, > before deciding whether this word is
6227 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6228 switch (ch) {
6229 case '>':
6230 redir_fd = redirect_opt_num(&dest);
6231 if (done_word(&dest, &ctx)) {
6232 goto parse_error;
6233 }
6234 redir_style = REDIRECT_OVERWRITE;
6235 if (next == '>') {
6236 redir_style = REDIRECT_APPEND;
6237 ch = i_getch(input);
6238 nommu_addchr(&ctx.as_string, ch);
6239 }
6240#if 0
6241 else if (next == '(') {
6242 syntax_error(">(process) not supported");
6243 goto parse_error;
6244 }
6245#endif
6246 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6247 goto parse_error;
6248 continue; /* back to top of while (1) */
6249 case '<':
6250 redir_fd = redirect_opt_num(&dest);
6251 if (done_word(&dest, &ctx)) {
6252 goto parse_error;
6253 }
6254 redir_style = REDIRECT_INPUT;
6255 if (next == '<') {
6256 redir_style = REDIRECT_HEREDOC;
6257 heredoc_cnt++;
6258 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6259 ch = i_getch(input);
6260 nommu_addchr(&ctx.as_string, ch);
6261 } else if (next == '>') {
6262 redir_style = REDIRECT_IO;
6263 ch = i_getch(input);
6264 nommu_addchr(&ctx.as_string, ch);
6265 }
6266#if 0
6267 else if (next == '(') {
6268 syntax_error("<(process) not supported");
6269 goto parse_error;
6270 }
6271#endif
6272 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6273 goto parse_error;
6274 continue; /* back to top of while (1) */
6275 }
6276
6277 if (dest.o_assignment == MAYBE_ASSIGNMENT
6278 /* check that we are not in word in "a=1 2>word b=1": */
6279 && !ctx.pending_redirect
6280 ) {
6281 /* ch is a special char and thus this word
6282 * cannot be an assignment */
6283 dest.o_assignment = NOT_ASSIGNMENT;
6284 }
6285
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006286 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6287
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006288 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006289 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006290 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006291 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006292 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006293 if (ch == EOF || ch == '\n')
6294 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006295 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006296 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006297 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006298 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006299 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006300 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006301 }
6302 break;
6303 case '\\':
6304 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006305 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006306 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006307 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006308 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006309 if (ch != '\n') {
6310 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006311 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006312 o_addchr(&dest, ch);
6313 nommu_addchr(&ctx.as_string, ch);
6314 /* Example: echo Hello \2>file
6315 * we need to know that word 2 is quoted */
6316 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006317 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006318#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006319 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006320 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6321 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006322 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006323#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006324 break;
6325 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006326 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006327 debug_printf_parse("parse_stream parse error: "
6328 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006329 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006330 }
Eric Andersen25f27032001-04-26 23:22:31 +00006331 break;
6332 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006333 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006334 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006335 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006336 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006337 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006338 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006339 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006340 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006341 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006342 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006343 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006344 }
Eric Andersen25f27032001-04-26 23:22:31 +00006345 break;
6346 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006347 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006348 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006349 if (dest.o_assignment == NOT_ASSIGNMENT)
6350 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006351 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006352#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006353 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006354#if !BB_MMU
6355 int pos;
6356#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006357 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6358 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006359#if !BB_MMU
6360 pos = dest.length;
6361#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006362 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006363#if !BB_MMU
6364 o_addstr(&ctx.as_string, dest.data + pos);
6365 o_addchr(&ctx.as_string, '`');
6366#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006367 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6368 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006369 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006370 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006371#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006372 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006373#if ENABLE_HUSH_CASE
6374 case_semi:
6375#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006376 if (done_word(&dest, &ctx)) {
6377 goto parse_error;
6378 }
6379 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006380#if ENABLE_HUSH_CASE
6381 /* Eat multiple semicolons, detect
6382 * whether it means something special */
6383 while (1) {
6384 ch = i_peek(input);
6385 if (ch != ';')
6386 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006387 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006388 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006389 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006390 ctx.ctx_dsemicolon = 1;
6391 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006392 break;
6393 }
6394 }
6395#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006396 new_cmd:
6397 /* We just finished a cmd. New one may start
6398 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006399 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006400 break;
6401 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006402 if (done_word(&dest, &ctx)) {
6403 goto parse_error;
6404 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006405 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006406 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006407 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006408 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006409 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006410 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006411 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006412 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006413 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006414 if (done_word(&dest, &ctx)) {
6415 goto parse_error;
6416 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006417#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006418 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006419 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006420#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006421 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006422 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006423 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006424 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006425 } else {
6426 /* we could pick up a file descriptor choice here
6427 * with redirect_opt_num(), but bash doesn't do it.
6428 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006429 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00006430 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006431 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006432 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006433#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006434 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006435 if (ctx.ctx_res_w == RES_MATCH
6436 && ctx.command->argv == NULL /* not (word|(... */
6437 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006438 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006439 ) {
6440 continue;
6441 }
6442#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006443 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006444 if (parse_group(&dest, &ctx, input, ch) != 0) {
6445 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006446 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006447 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006448 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006449#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006450 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006451 goto case_semi;
6452#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006453 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006454 /* proper use of this character is caught by end_trigger:
6455 * if we see {, we call parse_group(..., end_trigger='}')
6456 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006457 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006458 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006459 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006460 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006461 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006462 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006463 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006464
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006465 parse_error:
6466 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006467 struct parse_context *pctx;
6468 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006469
6470 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006471 * Sample for finding leaks on syntax error recovery path.
6472 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006473 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006474 * Samples to catch leaks at execution:
6475 * while if (true | {true;}); then echo ok; fi; do break; done
6476 * 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 +00006477 */
6478 pctx = &ctx;
6479 do {
6480 /* Update pipe/command counts,
6481 * otherwise freeing may miss some */
6482 done_pipe(pctx, PIPE_SEQ);
6483 debug_printf_clean("freeing list %p from ctx %p\n",
6484 pctx->list_head, pctx);
6485 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006486 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006487 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006488#if !BB_MMU
6489 o_free_unsafe(&pctx->as_string);
6490#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006491 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006492 if (pctx != &ctx) {
6493 free(pctx);
6494 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006495 IF_HAS_KEYWORDS(pctx = p2;)
6496 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006497 /* Free text, clear all dest fields */
6498 o_free(&dest);
6499 /* If we are not in top-level parse, we return,
6500 * our caller will propagate error.
6501 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006502 if (end_trigger != ';') {
6503#if !BB_MMU
6504 if (pstring)
6505 *pstring = NULL;
6506#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006507 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006508 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006509 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006510 /* Discard cached input, force prompt */
6511 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006512 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006513 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006514 }
Eric Andersen25f27032001-04-26 23:22:31 +00006515}
6516
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006517/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006518 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6519 * end_trigger controls how often we stop parsing
6520 * NUL: parse all, execute, return
6521 * ';': parse till ';' or newline, execute, repeat till EOF
6522 */
6523static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006524{
Denys Vlasenko00243b02009-11-16 02:00:03 +01006525 /* Why we need empty flag?
6526 * An obscure corner case "false; ``; echo $?":
6527 * empty command in `` should still set $? to 0.
6528 * But we can't just set $? to 0 at the start,
6529 * this breaks "false; echo `echo $?`" case.
6530 */
6531 bool empty = 1;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006532 while (1) {
6533 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006534
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006535 pipe_list = parse_stream(NULL, inp, end_trigger);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006536 if (!pipe_list) { /* EOF */
6537 if (empty)
6538 G.last_exitcode = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006539 break;
Denys Vlasenko00243b02009-11-16 02:00:03 +01006540 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006541 debug_print_tree(pipe_list, 0);
6542 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6543 run_and_free_list(pipe_list);
Denys Vlasenko00243b02009-11-16 02:00:03 +01006544 empty = 0;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006545 }
Eric Andersen25f27032001-04-26 23:22:31 +00006546}
6547
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006548static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006549{
6550 struct in_str input;
6551 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006552 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006553}
6554
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006555static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006556{
Eric Andersen25f27032001-04-26 23:22:31 +00006557 struct in_str input;
6558 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006559 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006560}
6561
Denis Vlasenkof9375282009-04-05 19:13:39 +00006562/* Called a few times only (or even once if "sh -c") */
6563static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006564{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006565 unsigned sig;
6566 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006567
Denis Vlasenkof9375282009-04-05 19:13:39 +00006568 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006569 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006570 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006571 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006572 mask |= SPECIAL_JOB_SIGS;
6573 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006574 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006575
Denis Vlasenkof9375282009-04-05 19:13:39 +00006576 if (!second_time)
6577 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6578 sig = 0;
6579 while (mask) {
6580 if (mask & 1)
6581 sigaddset(&G.blocked_set, sig);
6582 mask >>= 1;
6583 sig++;
6584 }
6585 sigdelset(&G.blocked_set, SIGCHLD);
6586
6587 sigprocmask(SIG_SETMASK, &G.blocked_set,
6588 second_time ? NULL : &G.inherited_set);
6589 /* POSIX allows shell to re-enable SIGCHLD
6590 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006591#if ENABLE_HUSH_FAST
6592 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006593 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006594 signal(SIGCHLD, SIGCHLD_handler);
6595#else
6596 if (!second_time)
6597 signal(SIGCHLD, SIG_DFL);
6598#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006599}
6600
6601#if ENABLE_HUSH_JOB
6602/* helper */
6603static void maybe_set_to_sigexit(int sig)
6604{
6605 void (*handler)(int);
6606 /* non_DFL_mask'ed signals are, well, masked,
6607 * no need to set handler for them.
6608 */
6609 if (!((G.non_DFL_mask >> sig) & 1)) {
6610 handler = signal(sig, sigexit);
6611 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6612 signal(sig, handler);
6613 }
6614}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006615/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006616static void set_fatal_handlers(void)
6617{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006618 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006619 if (HUSH_DEBUG) {
6620 maybe_set_to_sigexit(SIGILL );
6621 maybe_set_to_sigexit(SIGFPE );
6622 maybe_set_to_sigexit(SIGBUS );
6623 maybe_set_to_sigexit(SIGSEGV);
6624 maybe_set_to_sigexit(SIGTRAP);
6625 } /* else: hush is perfect. what SEGV? */
6626 maybe_set_to_sigexit(SIGABRT);
6627 /* bash 3.2 seems to handle these just like 'fatal' ones */
6628 maybe_set_to_sigexit(SIGPIPE);
6629 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006630 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006631 * if we aren't interactive... but in this case
6632 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006633 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006634 /*maybe_set_to_sigexit(SIGTERM);*/
6635 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006636}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006637#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006638
Denis Vlasenkod5762932009-03-31 11:22:57 +00006639static int set_mode(const char cstate, const char mode)
6640{
6641 int state = (cstate == '-' ? 1 : 0);
6642 switch (mode) {
6643 case 'n': G.fake_mode = state; break;
6644 case 'x': /*G.debug_mode = state;*/ break;
6645 default: return EXIT_FAILURE;
6646 }
6647 return EXIT_SUCCESS;
6648}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006649
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006650int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006651int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006652{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006653 static const struct variable const_shell_ver = {
6654 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006655 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006656 .max_len = 1, /* 0 can provoke free(name) */
6657 .flg_export = 1,
6658 .flg_read_only = 1,
6659 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006660 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006661 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006662 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006663 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006664 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006665
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006666 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006667 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006668 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006669#if !BB_MMU
6670 G.argv0_for_re_execing = argv[0];
6671#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006672 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006673 G.shell_ver = const_shell_ver; /* copying struct here */
6674 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006675 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006676 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6677 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006678 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006679 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006680 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006681 if (e) while (*e) {
6682 char *value = strchr(*e, '=');
6683 if (value) { /* paranoia */
6684 cur_var->next = xzalloc(sizeof(*cur_var));
6685 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006686 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006687 cur_var->max_len = strlen(*e);
6688 cur_var->flg_export = 1;
6689 }
6690 e++;
6691 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006692 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006693 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006694 putenv((char *)hush_version_str);
6695
6696 /* Export PWD */
6697 set_pwd_var(/*exp:*/ 1);
6698 /* bash also exports SHLVL and _,
6699 * and sets (but doesn't export) the following variables:
6700 * BASH=/bin/bash
6701 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6702 * BASH_VERSION='3.2.0(1)-release'
6703 * HOSTTYPE=i386
6704 * MACHTYPE=i386-pc-linux-gnu
6705 * OSTYPE=linux-gnu
6706 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02006707 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02006708 * EUID=<NNNNN>
6709 * UID=<NNNNN>
6710 * GROUPS=()
6711 * LINES=<NNN>
6712 * COLUMNS=<NNN>
6713 * BASH_ARGC=()
6714 * BASH_ARGV=()
6715 * BASH_LINENO=()
6716 * BASH_SOURCE=()
6717 * DIRSTACK=()
6718 * PIPESTATUS=([0]="0")
6719 * HISTFILE=/<xxx>/.bash_history
6720 * HISTFILESIZE=500
6721 * HISTSIZE=500
6722 * MAILCHECK=60
6723 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6724 * SHELL=/bin/bash
6725 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6726 * TERM=dumb
6727 * OPTERR=1
6728 * OPTIND=1
6729 * IFS=$' \t\n'
6730 * PS1='\s-\v\$ '
6731 * PS2='> '
6732 * PS4='+ '
6733 */
6734
Denis Vlasenko38f63192007-01-22 09:03:07 +00006735#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006736 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006737#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006738 G.global_argc = argc;
6739 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006740 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006741 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006742
Denis Vlasenkoed782372009-04-10 00:45:02 +00006743 if (setjmp(die_jmp)) {
6744 /* xfunc has failed! die die die */
6745 /* no EXIT traps, this is an escape hatch! */
6746 G.exiting = 1;
6747 hush_exit(xfunc_error_retval);
6748 }
6749
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006750 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006751 * block_signals(0) if we are going to execute "sh <script>",
6752 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006753 * If we later decide that we are interactive, we run block_signals(0)
6754 * (or re-run block_signals(1) if we ran block_signals(0) before)
6755 * in order to intercept (more) signals.
6756 */
6757
6758 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006759 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006760 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006761 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006762 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006763#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006764 "<:$:R:V:"
6765# if ENABLE_HUSH_FUNCTIONS
6766 "F:"
6767# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006768#endif
6769 );
6770 if (opt <= 0)
6771 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006772 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006773 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006774 /* Possibilities:
6775 * sh ... -c 'script'
6776 * sh ... -c 'script' ARG0 [ARG1...]
6777 * On NOMMU, if builtin_argc != 0,
6778 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6779 * "" needs to be replaced with NULL
6780 * and BARGV vector fed to builtin function.
6781 * Note: this form never happens:
6782 * sh ... -c 'builtin' [BARGV...] ""
6783 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02006784 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006785 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006786 G.root_ppid = getppid();
6787 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006788 G.global_argv = argv + optind;
6789 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006790 if (builtin_argc) {
6791 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6792 const struct built_in_command *x;
6793
6794 block_signals(0); /* 0: called 1st time */
6795 x = find_builtin(optarg);
6796 if (x) { /* paranoia */
6797 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6798 G.global_argv += builtin_argc;
6799 G.global_argv[-1] = NULL; /* replace "" */
6800 G.last_exitcode = x->function(argv + optind - 1);
6801 }
6802 goto final_return;
6803 }
6804 if (!G.global_argv[0]) {
6805 /* -c 'script' (no params): prevent empty $0 */
6806 G.global_argv--; /* points to argv[i] of 'script' */
6807 G.global_argv[0] = argv[0];
6808 G.global_argc--;
6809 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006810 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006811 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006812 goto final_return;
6813 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006814 /* Well, we cannot just declare interactiveness,
6815 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006816 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006817 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006818 case 's':
6819 /* "-s" means "read from stdin", but this is how we always
6820 * operate, so simply do nothing here. */
6821 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006822#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006823 case '<': /* "big heredoc" support */
6824 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6825 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006826 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006827 G.root_pid = bb_strtou(optarg, &optarg, 16);
6828 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02006829 G.root_ppid = bb_strtou(optarg, &optarg, 16);
6830 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006831 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6832 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006833 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006834 optarg++;
6835 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006836# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006837 optarg++;
6838 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006839# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006840 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006841 case 'R':
6842 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02006843 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006844 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006845# if ENABLE_HUSH_FUNCTIONS
6846 case 'F': {
6847 struct function *funcp = new_function(optarg);
6848 /* funcp->name is already set to optarg */
6849 /* funcp->body is set to NULL. It's a special case. */
6850 funcp->body_as_string = argv[optind];
6851 optind++;
6852 break;
6853 }
6854# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006855#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006856 case 'n':
6857 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006858 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006859 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006860 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006861#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006862 fprintf(stderr, "Usage: sh [FILE]...\n"
6863 " or: sh -c command [args]...\n\n");
6864 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006865#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006866 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006867#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006868 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006869 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006870
Denys Vlasenkodea47882009-10-09 15:40:49 +02006871 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006872 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006873 G.root_ppid = getppid();
6874 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006875
6876 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006877 if (argv[0] && argv[0][0] == '-') {
6878 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006879 debug_printf("sourcing /etc/profile\n");
6880 input = fopen_for_read("/etc/profile");
6881 if (input != NULL) {
6882 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006883 block_signals(0); /* 0: called 1st time */
6884 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006885 parse_and_run_file(input);
6886 fclose(input);
6887 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006888 /* bash: after sourcing /etc/profile,
6889 * tries to source (in the given order):
6890 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006891 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006892 * bash also sources ~/.bash_logout on exit.
6893 * If called as sh, skips .bash_XXX files.
6894 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006895 }
6896
Denis Vlasenkof9375282009-04-05 19:13:39 +00006897 if (argv[optind]) {
6898 FILE *input;
6899 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006900 * "bash <script>" (which is never interactive (unless -i?))
6901 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006902 * If called as sh, does the same but with $ENV.
6903 */
6904 debug_printf("running script '%s'\n", argv[optind]);
6905 G.global_argv = argv + optind;
6906 G.global_argc = argc - optind;
6907 input = xfopen_for_read(argv[optind]);
6908 close_on_exec_on(fileno(input));
6909 if (!signal_mask_is_inited)
6910 block_signals(0); /* 0: called 1st time */
6911 parse_and_run_file(input);
6912#if ENABLE_FEATURE_CLEAN_UP
6913 fclose(input);
6914#endif
6915 goto final_return;
6916 }
6917
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006918 /* Up to here, shell was non-interactive. Now it may become one.
6919 * NB: don't forget to (re)run block_signals(0/1) as needed.
6920 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006921
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006922 /* A shell is interactive if the '-i' flag was given,
6923 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006924 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006925 * no arguments remaining or the -s flag given
6926 * standard input is a terminal
6927 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006928 * Refer to Posix.2, the description of the 'sh' utility.
6929 */
6930#if ENABLE_HUSH_JOB
6931 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04006932 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6933 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6934 if (G_saved_tty_pgrp < 0)
6935 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006936
6937 /* try to dup stdin to high fd#, >= 255 */
6938 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6939 if (G_interactive_fd < 0) {
6940 /* try to dup to any fd */
6941 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006942 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006943 /* give up */
6944 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04006945 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006946 }
6947 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006948// TODO: track & disallow any attempts of user
6949// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006950 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006951 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006952 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006953 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006954
Mike Frysinger38478a62009-05-20 04:48:06 -04006955 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006956 /* If we were run as 'hush &', sleep until we are
6957 * in the foreground (tty pgrp == our pgrp).
6958 * If we get started under a job aware app (like bash),
6959 * make sure we are now in charge so we don't fight over
6960 * who gets the foreground */
6961 while (1) {
6962 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04006963 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6964 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006965 break;
6966 /* send TTIN to ourself (should stop us) */
6967 kill(- shell_pgrp, SIGTTIN);
6968 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006969 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006970
Denis Vlasenkof9375282009-04-05 19:13:39 +00006971 /* Block some signals */
6972 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006973
Mike Frysinger38478a62009-05-20 04:48:06 -04006974 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006975 /* Set other signals to restore saved_tty_pgrp */
6976 set_fatal_handlers();
6977 /* Put ourselves in our own process group
6978 * (bash, too, does this only if ctty is available) */
6979 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6980 /* Grab control of the terminal */
6981 tcsetpgrp(G_interactive_fd, getpid());
6982 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006983 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006984 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006985 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006986 } else if (!signal_mask_is_inited) {
6987 block_signals(0); /* 0: called 1st time */
6988 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006989#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006990 /* No job control compiled in, only prompt/line editing */
6991 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006992 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6993 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006994 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006995 G_interactive_fd = dup(STDIN_FILENO);
6996 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006997 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006998 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006999 }
7000 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007001 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00007002 close_on_exec_on(G_interactive_fd);
7003 block_signals(signal_mask_is_inited);
7004 } else if (!signal_mask_is_inited) {
7005 block_signals(0);
7006 }
7007#else
7008 /* We have interactiveness code disabled */
7009 if (!signal_mask_is_inited) {
7010 block_signals(0);
7011 }
7012#endif
7013 /* bash:
7014 * if interactive but not a login shell, sources ~/.bashrc
7015 * (--norc turns this off, --rcfile <file> overrides)
7016 */
7017
7018 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02007019 /* note: ash and hush share this string */
7020 printf("\n\n%s %s\n"
7021 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
7022 "\n",
7023 bb_banner,
7024 "hush - the humble shell"
7025 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00007026 }
7027
Denis Vlasenkof9375282009-04-05 19:13:39 +00007028 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00007029
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007030 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00007031#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00007032 if (G.cwd != bb_msg_unknown)
7033 free((char*)G.cwd);
7034 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007035 while (cur_var) {
7036 struct variable *tmp = cur_var;
7037 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00007038 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00007039 cur_var = cur_var->next;
7040 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00007041 }
Eric Andersen25f27032001-04-26 23:22:31 +00007042#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007043 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00007044}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007045
7046
7047#if ENABLE_LASH
7048int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7049int lash_main(int argc, char **argv)
7050{
Denys Vlasenko07934912009-08-20 03:40:04 +02007051 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00007052 return hush_main(argc, argv);
7053}
7054#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007055
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02007056#if ENABLE_MSH
7057int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7058int msh_main(int argc, char **argv)
7059{
7060 //bb_error_msg("msh is deprecated, please use hush instead");
7061 return hush_main(argc, argv);
7062}
7063#endif
7064
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007065
7066/*
7067 * Built-ins
7068 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007069static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007070{
7071 return 0;
7072}
7073
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007074static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007075{
7076 int argc = 0;
7077 while (*argv) {
7078 argc++;
7079 argv++;
7080 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02007081 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04007082}
7083
7084static int FAST_FUNC builtin_test(char **argv)
7085{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007086 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007087}
7088
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007089static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007090{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007091 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007092}
7093
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007094#if ENABLE_PRINTF
7095static int FAST_FUNC builtin_printf(char **argv)
7096{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007097 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04007098}
7099#endif
7100
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007101static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007102{
7103 int rcode = EXIT_SUCCESS;
7104
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007105 if (*++argv) {
7106 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007107 /* bash:
7108 * eval "echo Hi; done" ("done" is syntax error):
7109 * "echo Hi" will not execute too.
7110 */
7111 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007112 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007113 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007114 }
7115 return rcode;
7116}
7117
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007118static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007119{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007120 const char *newdir = argv[1];
7121 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007122 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007123 * bash says "bash: cd: HOME not set" and does nothing
7124 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007125 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02007126 const char *home = get_local_var_value("HOME");
7127 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007128 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007129 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007130 /* Mimic bash message exactly */
7131 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007132 return EXIT_FAILURE;
7133 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02007134 /* Read current dir (get_cwd(1) is inside) and set PWD.
7135 * Note: do not enforce exporting. If PWD was unset or unexported,
7136 * set it again, but do not export. bash does the same.
7137 */
7138 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007139 return EXIT_SUCCESS;
7140}
7141
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007142static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007143{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007144 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007145 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007146
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007147 /* Careful: we can end up here after [v]fork. Do not restore
7148 * tty pgrp then, only top-level shell process does that */
7149 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7150 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7151
Denys Vlasenko3ef4f772009-10-19 23:09:06 +02007152 /* TODO: if exec fails, bash does NOT exit! We do.
7153 * We'll need to undo sigprocmask (it's inside execvp_or_die)
7154 * and tcsetpgrp, and this is inherently racy.
7155 */
7156 execvp_or_die(argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007157}
7158
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007159static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007160{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007161 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007162
7163 /* interactive bash:
7164 * # trap "echo EEE" EXIT
7165 * # exit
7166 * exit
7167 * There are stopped jobs.
7168 * (if there are _stopped_ jobs, running ones don't count)
7169 * # exit
7170 * exit
7171 # EEE (then bash exits)
7172 *
7173 * we can use G.exiting = -1 as indicator "last cmd was exit"
7174 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007175
7176 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007177 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007178 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007179 /* mimic bash: exit 123abc == exit 255 + error msg */
7180 xfunc_error_retval = 255;
7181 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007182 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007183}
7184
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007185static void print_escaped(const char *s)
7186{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007187 if (*s == '\'')
7188 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007189 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007190 const char *p = strchrnul(s, '\'');
7191 /* print 'xxxx', possibly just '' */
7192 printf("'%.*s'", (int)(p - s), s);
7193 if (*p == '\0')
7194 break;
7195 s = p;
7196 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007197 /* s points to '; print "'''...'''" */
7198 putchar('"');
7199 do putchar('\''); while (*++s == '\'');
7200 putchar('"');
7201 } while (*s);
7202}
7203
Denys Vlasenko295fef82009-06-03 12:47:26 +02007204#if !ENABLE_HUSH_LOCAL
7205#define helper_export_local(argv, exp, lvl) \
7206 helper_export_local(argv, exp)
7207#endif
7208static void helper_export_local(char **argv, int exp, int lvl)
7209{
7210 do {
7211 char *name = *argv;
7212
7213 /* So far we do not check that name is valid (TODO?) */
7214
7215 if (strchr(name, '=') == NULL) {
7216 struct variable *var;
7217
7218 var = get_local_var(name);
7219 if (exp == -1) { /* unexporting? */
7220 /* export -n NAME (without =VALUE) */
7221 if (var) {
7222 var->flg_export = 0;
7223 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7224 unsetenv(name);
7225 } /* else: export -n NOT_EXISTING_VAR: no-op */
7226 continue;
7227 }
7228 if (exp == 1) { /* exporting? */
7229 /* export NAME (without =VALUE) */
7230 if (var) {
7231 var->flg_export = 1;
7232 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7233 putenv(var->varstr);
7234 continue;
7235 }
7236 }
7237 /* Exporting non-existing variable.
7238 * bash does not put it in environment,
7239 * but remembers that it is exported,
7240 * and does put it in env when it is set later.
7241 * We just set it to "" and export. */
7242 /* Or, it's "local NAME" (without =VALUE).
7243 * bash sets the value to "". */
7244 name = xasprintf("%s=", name);
7245 } else {
7246 /* (Un)exporting/making local NAME=VALUE */
7247 name = xstrdup(name);
7248 }
7249 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7250 } while (*++argv);
7251}
7252
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007253static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007254{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007255 unsigned opt_unexport;
7256
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007257#if ENABLE_HUSH_EXPORT_N
7258 /* "!": do not abort on errors */
7259 opt_unexport = getopt32(argv, "!n");
7260 if (opt_unexport == (uint32_t)-1)
7261 return EXIT_FAILURE;
7262 argv += optind;
7263#else
7264 opt_unexport = 0;
7265 argv++;
7266#endif
7267
7268 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007269 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007270 if (e) {
7271 while (*e) {
7272#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007273 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007274#else
7275 /* ash emits: export VAR='VAL'
7276 * bash: declare -x VAR="VAL"
7277 * we follow ash example */
7278 const char *s = *e++;
7279 const char *p = strchr(s, '=');
7280
7281 if (!p) /* wtf? take next variable */
7282 continue;
7283 /* export var= */
7284 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007285 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007286 putchar('\n');
7287#endif
7288 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007289 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007290 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007291 return EXIT_SUCCESS;
7292 }
7293
Denys Vlasenko295fef82009-06-03 12:47:26 +02007294 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007295
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007296 return EXIT_SUCCESS;
7297}
7298
Denys Vlasenko295fef82009-06-03 12:47:26 +02007299#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007300static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007301{
7302 if (G.func_nest_level == 0) {
7303 bb_error_msg("%s: not in a function", argv[0]);
7304 return EXIT_FAILURE; /* bash compat */
7305 }
7306 helper_export_local(argv, 0, G.func_nest_level);
7307 return EXIT_SUCCESS;
7308}
7309#endif
7310
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007311static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007312{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007313 int sig;
7314 char *new_cmd;
7315
7316 if (!G.traps)
7317 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7318
7319 argv++;
7320 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007321 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007322 /* No args: print all trapped */
7323 for (i = 0; i < NSIG; ++i) {
7324 if (G.traps[i]) {
7325 printf("trap -- ");
7326 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007327 /* note: bash adds "SIG", but only if invoked
7328 * as "bash". If called as "sh", or if set -o posix,
7329 * then it prints short signal names.
7330 * We are printing short names: */
7331 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007332 }
7333 }
Denys Vlasenko8131eea2009-11-02 14:19:51 +01007334 /*fflush_all(); - done after each builtin anyway */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007335 return EXIT_SUCCESS;
7336 }
7337
7338 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007339 /* If first arg is a number: reset all specified signals */
7340 sig = bb_strtou(*argv, NULL, 10);
7341 if (errno == 0) {
7342 int ret;
7343 process_sig_list:
7344 ret = EXIT_SUCCESS;
7345 while (*argv) {
7346 sig = get_signum(*argv++);
7347 if (sig < 0 || sig >= NSIG) {
7348 ret = EXIT_FAILURE;
7349 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007350 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007351 continue;
7352 }
7353
7354 free(G.traps[sig]);
7355 G.traps[sig] = xstrdup(new_cmd);
7356
7357 debug_printf("trap: setting SIG%s (%i) to '%s'",
7358 get_signame(sig), sig, G.traps[sig]);
7359
7360 /* There is no signal for 0 (EXIT) */
7361 if (sig == 0)
7362 continue;
7363
7364 if (new_cmd) {
7365 sigaddset(&G.blocked_set, sig);
7366 } else {
7367 /* There was a trap handler, we are removing it
7368 * (if sig has non-DFL handling,
7369 * we don't need to do anything) */
7370 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7371 continue;
7372 sigdelset(&G.blocked_set, sig);
7373 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007374 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007375 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007376 return ret;
7377 }
7378
7379 if (!argv[1]) { /* no second arg */
7380 bb_error_msg("trap: invalid arguments");
7381 return EXIT_FAILURE;
7382 }
7383
7384 /* First arg is "-": reset all specified to default */
7385 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7386 /* Everything else: set arg as signal handler
7387 * (includes "" case, which ignores signal) */
7388 if (argv[0][0] == '-') {
7389 if (argv[0][1] == '\0') { /* "-" */
7390 /* new_cmd remains NULL: "reset these sigs" */
7391 goto reset_traps;
7392 }
7393 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7394 argv++;
7395 }
7396 /* else: "-something", no special meaning */
7397 }
7398 new_cmd = *argv;
7399 reset_traps:
7400 argv++;
7401 goto process_sig_list;
7402}
7403
Mike Frysinger93cadc22009-05-27 17:06:25 -04007404/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007405static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007406{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007407 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007408
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007409 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007410 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007411 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007412
7413 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007414 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007415 type = "an alias";*/
7416#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007417 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007418 type = "a function";
7419#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007420 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007421 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007422 else if ((path = find_in_path(*argv)) != NULL)
7423 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007424 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007425 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007426 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007427 continue;
7428 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007429
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007430 printf("%s is %s\n", *argv, type);
7431 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007432 }
7433
7434 return ret;
7435}
7436
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007437#if ENABLE_HUSH_JOB
7438/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007439static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007440{
7441 int i, jobnum;
7442 struct pipe *pi;
7443
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007444 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007445 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007446
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007447 /* If they gave us no args, assume they want the last backgrounded task */
7448 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007449 for (pi = G.job_list; pi; pi = pi->next) {
7450 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007451 goto found;
7452 }
7453 }
7454 bb_error_msg("%s: no current job", argv[0]);
7455 return EXIT_FAILURE;
7456 }
7457 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7458 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7459 return EXIT_FAILURE;
7460 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007461 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007462 if (pi->jobid == jobnum) {
7463 goto found;
7464 }
7465 }
7466 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7467 return EXIT_FAILURE;
7468 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007469 /* TODO: bash prints a string representation
7470 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007471 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007472 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007473 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007474 }
7475
7476 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007477 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7478 for (i = 0; i < pi->num_cmds; i++) {
7479 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7480 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007481 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007482 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007483
7484 i = kill(- pi->pgrp, SIGCONT);
7485 if (i < 0) {
7486 if (errno == ESRCH) {
7487 delete_finished_bg_job(pi);
7488 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007489 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007490 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007491 }
7492
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007493 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007494 remove_bg_job(pi);
7495 return checkjobs_and_fg_shell(pi);
7496 }
7497 return EXIT_SUCCESS;
7498}
7499#endif
7500
7501#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007502static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007503{
7504 const struct built_in_command *x;
7505
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007506 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007507 "Built-in commands:\n"
7508 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007509 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7510 if (x->descr)
7511 printf("%s\t%s\n", x->cmd, x->descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007512 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007513 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007514 return EXIT_SUCCESS;
7515}
7516#endif
7517
7518#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007519static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007520{
7521 struct pipe *job;
7522 const char *status_string;
7523
Denis Vlasenko87a86552008-07-29 19:43:10 +00007524 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007525 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007526 status_string = "Stopped";
7527 else
7528 status_string = "Running";
7529
7530 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7531 }
7532 return EXIT_SUCCESS;
7533}
7534#endif
7535
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007536#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007537static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007538{
7539 void *p;
7540 unsigned long l;
7541
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007542# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007543 /* Optional. Reduces probability of false positives */
7544 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007545# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007546 /* Crude attempt to find where "free memory" starts,
7547 * sans fragmentation. */
7548 p = malloc(240);
7549 l = (unsigned long)p;
7550 free(p);
7551 p = malloc(3400);
7552 if (l < (unsigned long)p) l = (unsigned long)p;
7553 free(p);
7554
7555 if (!G.memleak_value)
7556 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007557
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007558 l -= G.memleak_value;
7559 if ((long)l < 0)
7560 l = 0;
7561 l /= 1024;
7562 if (l > 127)
7563 l = 127;
7564
7565 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7566 return l;
7567}
7568#endif
7569
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007570static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007571{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007572 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007573 return EXIT_SUCCESS;
7574}
7575
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007576static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007577{
7578 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007579 const char *name = "REPLY";
7580
7581 if (argv[1]) {
7582 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007583 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7584 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007585 if (!is_well_formed_var_name(name, '\0')) {
7586 /* Mimic bash message */
7587 bb_error_msg("read: '%s': not a valid identifier", name);
7588 return 1;
7589 }
7590 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007591
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007592//TODO: bash unbackslashes input, splits words and puts them in argv[i]
7593
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007594 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denys Vlasenko295fef82009-06-03 12:47:26 +02007595 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007596}
7597
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007598/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7599 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007600 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007601 * set [-abCefhmnuvx] [-o option] [argument...]
7602 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007603 * set -- [argument...]
7604 * set -o
7605 * set +o
7606 * Implementations shall support the options in both their hyphen and
7607 * plus-sign forms. These options can also be specified as options to sh.
7608 * Examples:
7609 * Write out all variables and their values: set
7610 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7611 * Turn on the -x and -v options: set -xv
7612 * Unset all positional parameters: set --
7613 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7614 * Set the positional parameters to the expansion of x, even if x expands
7615 * with a leading '-' or '+': set -- $x
7616 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007617 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007618 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007619static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007620{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007621 int n;
7622 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007623 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007624
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007625 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007626 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007627 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007628 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007629 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007630 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007631
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007632 do {
7633 if (!strcmp(arg, "--")) {
7634 ++argv;
7635 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007636 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007637 if (arg[0] != '+' && arg[0] != '-')
7638 break;
7639 for (n = 1; arg[n]; ++n)
7640 if (set_mode(arg[0], arg[n]))
7641 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007642 } while ((arg = *++argv) != NULL);
7643 /* Now argv[0] is 1st argument */
7644
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007645 if (arg == NULL)
7646 return EXIT_SUCCESS;
7647 set_argv:
7648
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007649 /* NB: G.global_argv[0] ($0) is never freed/changed */
7650 g_argv = G.global_argv;
7651 if (G.global_args_malloced) {
7652 pp = g_argv;
7653 while (*++pp)
7654 free(*pp);
7655 g_argv[1] = NULL;
7656 } else {
7657 G.global_args_malloced = 1;
7658 pp = xzalloc(sizeof(pp[0]) * 2);
7659 pp[0] = g_argv[0]; /* retain $0 */
7660 g_argv = pp;
7661 }
7662 /* This realloc's G.global_argv */
7663 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7664
7665 n = 1;
7666 while (*++pp)
7667 n++;
7668 G.global_argc = n;
7669
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007670 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007671
7672 /* Nothing known, so abort */
7673 error:
7674 bb_error_msg("set: %s: invalid option", arg);
7675 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007676}
7677
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007678static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007679{
7680 int n = 1;
7681 if (argv[1]) {
7682 n = atoi(argv[1]);
7683 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007684 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007685 if (G.global_args_malloced) {
7686 int m = 1;
7687 while (m <= n)
7688 free(G.global_argv[m++]);
7689 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007690 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007691 memmove(&G.global_argv[1], &G.global_argv[n+1],
7692 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007693 return EXIT_SUCCESS;
7694 }
7695 return EXIT_FAILURE;
7696}
7697
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007698static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007699{
Mike Frysinger93cadc22009-05-27 17:06:25 -04007700 char *arg_path;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007701 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007702 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007703#if ENABLE_HUSH_FUNCTIONS
7704 smallint sv_flg;
7705#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007706
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007707 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007708 return EXIT_FAILURE;
7709
Mike Frysinger93cadc22009-05-27 17:06:25 -04007710 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7711 input = fopen_for_read(arg_path);
7712 free(arg_path);
7713 } else
7714 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007715 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007716 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007717 return EXIT_FAILURE;
7718 }
7719 close_on_exec_on(fileno(input));
7720
Mike Frysinger885b6f22009-04-18 21:04:25 +00007721#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007722 sv_flg = G.flag_return_in_progress;
7723 /* "we are inside sourced file, ok to use return" */
7724 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007725#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007726 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007727
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007728 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007729 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007730
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007731 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007732#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007733 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007734#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007735
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007736 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007737}
7738
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007739static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007740{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007741 int rc;
7742 mode_t mask;
7743
7744 mask = umask(0);
7745 if (argv[1]) {
7746 mode_t old_mask = mask;
7747
7748 mask ^= 0777;
7749 rc = bb_parse_mode(argv[1], &mask);
7750 mask ^= 0777;
7751 if (rc == 0) {
7752 mask = old_mask;
7753 /* bash messages:
7754 * bash: umask: 'q': invalid symbolic mode operator
7755 * bash: umask: 999: octal number out of range
7756 */
7757 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007758 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007759 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007760 rc = 1;
7761 /* Mimic bash */
7762 printf("%04o\n", (unsigned) mask);
7763 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007764 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007765 umask(mask);
7766
7767 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007768}
7769
Mike Frysingerd690f682009-03-30 06:50:54 +00007770/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007771static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007772{
Mike Frysingerd690f682009-03-30 06:50:54 +00007773 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007774 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007775
Denis Vlasenko28e67962009-04-26 23:22:40 +00007776 /* "!": do not abort on errors */
7777 /* "+": stop at 1st non-option */
7778 opts = getopt32(argv, "!+vf");
7779 if (opts == (unsigned)-1)
7780 return EXIT_FAILURE;
7781 if (opts == 3) {
7782 bb_error_msg("unset: -v and -f are exclusive");
7783 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007784 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007785 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007786
7787 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007788 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007789 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007790 if (unset_local_var(*argv)) {
7791 /* unset <nonexistent_var> doesn't fail.
7792 * Error is when one tries to unset RO var.
7793 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007794 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007795 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007796 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007797#if ENABLE_HUSH_FUNCTIONS
7798 else {
7799 unset_func(*argv);
7800 }
7801#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007802 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007803 }
7804 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007805}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007806
Mike Frysinger56bdea12009-03-28 20:01:58 +00007807/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007808static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00007809{
7810 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007811 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007812
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007813 if (*++argv == NULL) {
7814 /* Don't care about wait results */
7815 /* Note 1: must wait until there are no more children */
7816 /* Note 2: must be interruptible */
7817 /* Examples:
7818 * $ sleep 3 & sleep 6 & wait
7819 * [1] 30934 sleep 3
7820 * [2] 30935 sleep 6
7821 * [1] Done sleep 3
7822 * [2] Done sleep 6
7823 * $ sleep 3 & sleep 6 & wait
7824 * [1] 30936 sleep 3
7825 * [2] 30937 sleep 6
7826 * [1] Done sleep 3
7827 * ^C <-- after ~4 sec from keyboard
7828 * $
7829 */
7830 sigaddset(&G.blocked_set, SIGCHLD);
7831 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7832 while (1) {
7833 checkjobs(NULL);
7834 if (errno == ECHILD)
7835 break;
7836 /* Wait for SIGCHLD or any other signal of interest */
7837 /* sigtimedwait with infinite timeout: */
7838 sig = sigwaitinfo(&G.blocked_set, NULL);
7839 if (sig > 0) {
7840 sig = check_and_run_traps(sig);
7841 if (sig && sig != SIGCHLD) { /* see note 2 */
7842 ret = 128 + sig;
7843 break;
7844 }
7845 }
7846 }
7847 sigdelset(&G.blocked_set, SIGCHLD);
7848 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7849 return ret;
7850 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007851
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007852 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007853 while (*argv) {
7854 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007855 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007856 /* mimic bash message */
7857 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007858 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007859 }
7860 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007861 if (WIFSIGNALED(status))
7862 ret = 128 + WTERMSIG(status);
7863 else if (WIFEXITED(status))
7864 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007865 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007866 ret = EXIT_FAILURE;
7867 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007868 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007869 ret = 127;
7870 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007871 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007872 }
7873
7874 return ret;
7875}
7876
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007877#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7878static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7879{
7880 if (argv[1]) {
7881 def = bb_strtou(argv[1], NULL, 10);
7882 if (errno || def < def_min || argv[2]) {
7883 bb_error_msg("%s: bad arguments", argv[0]);
7884 def = UINT_MAX;
7885 }
7886 }
7887 return def;
7888}
7889#endif
7890
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007891#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007892static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007893{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007894 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007895 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007896 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007897 return EXIT_SUCCESS; /* bash compat */
7898 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007899 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007900
7901 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7902 if (depth == UINT_MAX)
7903 G.flag_break_continue = BC_BREAK;
7904 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007905 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007906
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007907 return EXIT_SUCCESS;
7908}
7909
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007910static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007911{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007912 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7913 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007914}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007915#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007916
7917#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007918static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007919{
7920 int rc;
7921
7922 if (G.flag_return_in_progress != -1) {
7923 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7924 return EXIT_FAILURE; /* bash compat */
7925 }
7926
7927 G.flag_return_in_progress = 1;
7928
7929 /* bash:
7930 * out of range: wraps around at 256, does not error out
7931 * non-numeric param:
7932 * f() { false; return qwe; }; f; echo $?
7933 * bash: return: qwe: numeric argument required <== we do this
7934 * 255 <== we also do this
7935 */
7936 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7937 return rc;
7938}
7939#endif