blob: ae08c73269d14c385523f1416e6b074780408bcd [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;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000457#if !BB_MMU
458 char *body_as_string;
459#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
1209 fflush(NULL); /* flush all streams */
1210 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);
1682 fflush(stdout);
1683 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
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002006/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00002007 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002008static int o_glob(o_string *o, int n)
2009{
2010 glob_t globdata;
2011 int gr;
2012 char *pattern;
2013
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002014 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002015 if (!o->data)
2016 return o_save_ptr_helper(o, n);
2017 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002018 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002019 if (!glob_needed(pattern)) {
2020 literal:
2021 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002022 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002023 return o_save_ptr_helper(o, n);
2024 }
2025
2026 memset(&globdata, 0, sizeof(globdata));
2027 gr = glob(pattern, 0, NULL, &globdata);
2028 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2029 if (gr == GLOB_NOSPACE)
2030 bb_error_msg_and_die("out of memory during glob");
2031 if (gr == GLOB_NOMATCH) {
2032 globfree(&globdata);
2033 goto literal;
2034 }
2035 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002036 /* TODO: testcase for bad glob pattern behavior */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002037 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2038 }
2039 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2040 char **argv = globdata.gl_pathv;
2041 o->length = pattern - o->data; /* "forget" pattern */
2042 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002043 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002044 n = o_save_ptr_helper(o, n);
2045 argv++;
2046 if (!*argv)
2047 break;
2048 }
2049 }
2050 globfree(&globdata);
2051 if (DEBUG_GLOB)
2052 debug_print_list("o_glob returning", o, n);
2053 return n;
2054}
2055
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002056/* If o->o_glob == 1, glob the string so far remembered.
2057 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002058static int o_save_ptr(o_string *o, int n)
2059{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002060 if (o->o_glob) { /* if globbing is requested */
2061 /* If o->has_empty_slot, list[n] was already globbed
2062 * (if it was requested back then when it was filled)
2063 * so don't do that again! */
2064 if (!o->has_empty_slot)
2065 return o_glob(o, n); /* o_save_ptr_helper is inside */
2066 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002067 return o_save_ptr_helper(o, n);
2068}
2069
2070/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002071static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002072{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002073 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002074 int string_start;
2075
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002076 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2077 if (DEBUG_EXPAND)
2078 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002079 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002080 list = (char**)o->data;
2081 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2082 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002083 while (n) {
2084 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002085 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002086 }
2087 return list;
2088}
2089
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002090
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002091/* Expansion can recurse */
2092#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002093static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002094#endif
2095static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002096#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002097#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002098 parse_stream_dquoted(dest, input, dquote_end)
2099#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002100static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002101 o_string *dest,
2102 struct in_str *input,
2103 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002104
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002105/* expand_strvec_to_strvec() takes a list of strings, expands
2106 * all variable references within and returns a pointer to
2107 * a list of expanded strings, possibly with larger number
2108 * of strings. (Think VAR="a b"; echo $VAR).
2109 * This new list is allocated as a single malloc block.
2110 * NULL-terminated list of char* pointers is at the beginning of it,
2111 * followed by strings themself.
2112 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002113
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002114/* Store given string, finalizing the word and starting new one whenever
2115 * we encounter IFS char(s). This is used for expanding variable values.
2116 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2117static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002118{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002119 while (1) {
2120 int word_len = strcspn(str, G.ifs);
2121 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002122 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123 o_addQstr(output, str, word_len);
2124 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002125 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002126 str += word_len;
2127 }
2128 if (!*str) /* EOL - do not finalize word */
2129 break;
2130 o_addchr(output, '\0');
2131 debug_print_list("expand_on_ifs", output, n);
2132 n = o_save_ptr(output, n);
2133 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002134 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002135 debug_print_list("expand_on_ifs[1]", output, n);
2136 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002137}
2138
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002139/* Helper to expand $((...)) and heredoc body. These act as if
2140 * they are in double quotes, with the exception that they are not :).
2141 * Just the rules are similar: "expand only $var and `cmd`"
2142 *
2143 * Returns malloced string.
2144 * As an optimization, we return NULL if expansion is not needed.
2145 */
2146static char *expand_pseudo_dquoted(const char *str)
2147{
2148 char *exp_str;
2149 struct in_str input;
2150 o_string dest = NULL_O_STRING;
2151
2152 if (strchr(str, '$') == NULL
2153#if ENABLE_HUSH_TICK
2154 && strchr(str, '`') == NULL
2155#endif
2156 ) {
2157 return NULL;
2158 }
2159
2160 /* We need to expand. Example:
2161 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2162 */
2163 setup_string_in_str(&input, str);
2164 parse_stream_dquoted(NULL, &dest, &input, EOF);
2165 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2166 exp_str = expand_string_to_string(dest.data);
2167 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2168 o_free_unsafe(&dest);
2169 return exp_str;
2170}
2171
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002172/* Expand all variable references in given string, adding words to list[]
2173 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2174 * to be filled). This routine is extremely tricky: has to deal with
2175 * variables/parameters with whitespace, $* and $@, and constructs like
2176 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02002177static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002178{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002179 /* or_mask is either 0 (normal case) or 0x80 -
2180 * expansion of right-hand side of assignment == 1-element expand.
2181 * It will also do no globbing, and thus we must not backslash-quote!
2182 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002183 char ored_ch;
2184 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002185
2186 ored_ch = 0;
2187
Denys Vlasenkof37eb392009-10-18 11:46:35 +02002188 debug_printf_expand("expand_vars_to_list: arg:'%s' or_mask:%x\n", arg, or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002189 debug_print_list("expand_vars_to_list", output, n);
2190 n = o_save_ptr(output, n);
2191 debug_print_list("expand_vars_to_list[0]", output, n);
2192
2193 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002194 char first_ch;
2195 int i;
2196 char *dyn_val = NULL;
2197 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198#if ENABLE_HUSH_TICK
2199 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002200#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002201#if ENABLE_SH_MATH_SUPPORT
2202 char arith_buf[sizeof(arith_t)*3 + 2];
2203#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002204 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002205 debug_print_list("expand_vars_to_list[1]", output, n);
2206 arg = ++p;
2207 p = strchr(p, SPECIAL_VAR_SYMBOL);
2208
2209 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2210 /* "$@" is special. Even if quoted, it can still
2211 * expand to nothing (not even an empty string) */
2212 if ((first_ch & 0x7f) != '@')
2213 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002214
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002215 switch (first_ch & 0x7f) {
2216 /* Highest bit in first_ch indicates that var is double-quoted */
2217 case '$': /* pid */
2218 val = utoa(G.root_pid);
2219 break;
2220 case '!': /* bg pid */
2221 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2222 break;
2223 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002224 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002225 break;
2226 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002227 if (arg[1] != SPECIAL_VAR_SYMBOL)
2228 /* actually, it's a ${#var} */
2229 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002230 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2231 break;
2232 case '*':
2233 case '@':
2234 i = 1;
2235 if (!G.global_argv[i])
2236 break;
2237 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2238 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002239 smallint sv = output->o_escape;
2240 /* unquoted var's contents should be globbed, so don't escape */
2241 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002242 while (G.global_argv[i]) {
2243 n = expand_on_ifs(output, n, G.global_argv[i]);
2244 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2245 if (G.global_argv[i++][0] && G.global_argv[i]) {
2246 /* this argv[] is not empty and not last:
2247 * put terminating NUL, start new word */
2248 o_addchr(output, '\0');
2249 debug_print_list("expand_vars_to_list[2]", output, n);
2250 n = o_save_ptr(output, n);
2251 debug_print_list("expand_vars_to_list[3]", output, n);
2252 }
2253 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002254 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002255 } else
2256 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2257 * and in this case should treat it like '$*' - see 'else...' below */
2258 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2259 while (1) {
2260 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2261 if (++i >= G.global_argc)
2262 break;
2263 o_addchr(output, '\0');
2264 debug_print_list("expand_vars_to_list[4]", output, n);
2265 n = o_save_ptr(output, n);
2266 }
2267 } else { /* quoted $*: add as one word */
2268 while (1) {
2269 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2270 if (!G.global_argv[++i])
2271 break;
2272 if (G.ifs[0])
2273 o_addchr(output, G.ifs[0]);
2274 }
2275 }
2276 break;
2277 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2278 /* "Empty variable", used to make "" etc to not disappear */
2279 arg++;
2280 ored_ch = 0x80;
2281 break;
2282#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002283 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002284 *p = '\0';
2285 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002286 /* Can't just stuff it into output o_string,
2287 * expanded result may need to be globbed
2288 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002289 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002290 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002291 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2292 val = subst_result.data;
2293 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002294#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002295#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002296 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002297 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002298 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002299 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002300 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002301
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002302 arg++; /* skip '+' */
2303 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002304 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002305
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002306 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002307 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002308 hooks.setvar = arith_set_local_var;
2309 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002310 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2311 free(exp_str);
2312
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002313 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002314 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002315 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002316 case -3:
2317 msg = "exponent less than 0";
2318 break;
2319 case -2:
2320 msg = "divide by 0";
2321 break;
2322 case -5:
2323 msg = "expression recursion loop detected";
2324 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002325 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002326 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002327 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002328 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002329 sprintf(arith_buf, arith_t_fmt, res);
2330 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002331 break;
2332 }
2333#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002334 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002335 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002336 bool exp_len = false;
2337 bool exp_null = false;
2338 char *var = arg;
2339 char exp_save = exp_save; /* for compiler */
2340 char exp_op = exp_op; /* for compiler */
2341 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002342 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002343
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002344 *p = '\0';
2345 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002346
2347 /* prepare for expansions */
2348 if (var[0] == '#') {
2349 /* handle length expansion ${#var} */
2350 exp_len = true;
2351 ++var;
2352 } else {
2353 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002354 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002355 if (!var[exp_off])
2356 exp_off = 0;
2357 if (exp_off) {
2358 exp_save = var[exp_off];
2359 exp_null = exp_save == ':';
2360 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002361 if (exp_null)
2362 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002363 exp_op = *exp_word++;
2364 var[exp_off] = '\0';
2365 }
2366 }
2367
2368 /* lookup the variable in question */
2369 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002370 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002371 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002372 if (i < G.global_argc)
2373 val = G.global_argv[i];
2374 /* else val remains NULL: $N with too big N */
2375 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002376 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002377
2378 /* handle any expansions */
2379 if (exp_len) {
2380 debug_printf_expand("expand: length of '%s' = ", val);
2381 val = utoa(val ? strlen(val) : 0);
2382 debug_printf_expand("%s\n", val);
2383 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002384 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002385 if (val) {
2386 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002387 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002388 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002389 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002390 if (exp_op == *exp_word) /* ## or %% */
2391 ++exp_word;
2392 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002393 loc = scan(dyn_val, exp_word, match_at_left);
2394 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002395 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002396 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002397 *loc = '\0';
2398 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002399 } else {
2400 /* we need to do an expansion */
2401 int exp_test = (!val || (exp_null && !val[0]));
2402 if (exp_op == '+')
2403 exp_test = !exp_test;
2404 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2405 exp_null ? "true" : "false", exp_test);
2406 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002407 if (exp_op == '?') {
2408//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002409 /* ${var?[error_msg_if_unset]} */
2410 /* ${var:?[error_msg_if_unset_or_null]} */
2411 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002412 die_if_script("%s: %s",
2413 var,
2414 exp_word[0] ? exp_word : "parameter null or not set"
2415 );
2416 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002417 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002418 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002419
Mike Frysingera4f331d2009-04-07 06:03:22 +00002420 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002421 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002422 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002423 /* mimic bash message */
2424 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002425 val = NULL;
2426 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002427 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002428 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002429 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002430 }
2431 }
2432 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002433
Mike Frysinger6379bb42009-03-28 18:55:03 +00002434 var[exp_off] = exp_save;
2435 }
2436
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002437 arg[0] = first_ch;
2438#if ENABLE_HUSH_TICK
2439 store_val:
2440#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002441 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002442 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002443 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002444 /* unquoted var's contents should be globbed, so don't escape */
2445 smallint sv = output->o_escape;
2446 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002447 n = expand_on_ifs(output, n, val);
2448 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002449 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002450 }
2451 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002452 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002453 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002454 } /* default: */
2455 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002456
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002457 if (val) {
2458 o_addQstr(output, val, strlen(val));
2459 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002460 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002461 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002462 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002463 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002464
2465#if ENABLE_HUSH_TICK
2466 o_free(&subst_result);
2467#endif
2468 arg = ++p;
2469 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2470
2471 if (arg[0]) {
2472 debug_print_list("expand_vars_to_list[a]", output, n);
2473 /* this part is literal, and it was already pre-quoted
2474 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002475 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002476 debug_print_list("expand_vars_to_list[b]", output, n);
2477 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2478 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2479 ) {
2480 n--;
2481 /* allow to reuse list[n] later without re-growth */
2482 output->has_empty_slot = 1;
2483 } else {
2484 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002485 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002486 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002487}
2488
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002490{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002491 int n;
2492 char **list;
2493 char **v;
2494 o_string output = NULL_O_STRING;
2495
2496 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002497 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002498 /* (unquoted $var will temporarily switch it off) */
2499 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002500 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002501
2502 n = 0;
2503 v = argv;
2504 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002505 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002506 v++;
2507 }
2508 debug_print_list("expand_variables", &output, n);
2509
2510 /* output.data (malloced in one block) gets returned in "list" */
2511 list = o_finalize_list(&output, n);
2512 debug_print_strings("expand_variables[1]", list);
2513 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002514}
2515
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002516static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002517{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002518 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002519}
2520
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002521#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002522static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2523{
2524 return expand_variables(argv, 0x80);
2525}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002526#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002527
2528#ifdef CMD_SINGLEWORD_NOGLOB_COND
2529static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2530{
2531 int n;
2532 char **list;
2533 char **v;
2534 o_string output = NULL_O_STRING;
2535
2536 n = 0;
2537 v = argv;
2538 while (*v) {
2539 int is_var = is_well_formed_var_name(*v, '=');
2540 /* is_var * 0x80: singleword expansion for vars */
2541 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2542
2543 /* Subtle! expand_vars_to_list did not glob last word yet.
2544 * It does this only when fed with further data.
2545 * Therefore we set globbing flags AFTER it, not before:
2546 */
2547
2548 /* if it is not recognizably abc=...; then: */
2549 output.o_escape = !is_var; /* protect against globbing for "$var" */
2550 /* (unquoted $var will temporarily switch it off) */
2551 output.o_glob = !is_var; /* and indeed do globbing */
2552 v++;
2553 }
2554 debug_print_list("expand_cond", &output, n);
2555
2556 /* output.data (malloced in one block) gets returned in "list" */
2557 list = o_finalize_list(&output, n);
2558 debug_print_strings("expand_cond[1]", list);
2559 return list;
2560}
2561#endif
2562
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002563/* Used for expansion of right hand of assignments */
2564/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2565 * "v=/bin/c*" */
2566static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002567{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002568 char *argv[2], **list;
2569
2570 argv[0] = (char*)str;
2571 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002572 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002573 if (HUSH_DEBUG)
2574 if (!list[0] || list[1])
2575 bb_error_msg_and_die("BUG in varexp2");
2576 /* actually, just move string 2*sizeof(char*) bytes back */
2577 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002578 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002579 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2580 return (char*)list;
2581}
2582
2583/* Used for "eval" builtin */
2584static char* expand_strvec_to_string(char **argv)
2585{
2586 char **list;
2587
2588 list = expand_variables(argv, 0x80);
2589 /* Convert all NULs to spaces */
2590 if (list[0]) {
2591 int n = 1;
2592 while (list[n]) {
2593 if (HUSH_DEBUG)
2594 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2595 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002596 /* bash uses ' ' regardless of $IFS contents */
2597 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002598 n++;
2599 }
2600 }
2601 overlapping_strcpy((char*)list, list[0]);
2602 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2603 return (char*)list;
2604}
2605
2606static char **expand_assignments(char **argv, int count)
2607{
2608 int i;
2609 char **p = NULL;
2610 /* Expand assignments into one string each */
2611 for (i = 0; i < count; i++) {
2612 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2613 }
2614 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002615}
2616
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002617
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002618#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002619/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002620void re_execute_shell(char ***to_free, const char *s,
2621 char *g_argv0, char **g_argv,
2622 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002623
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002624static void reset_traps_to_defaults(void)
2625{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002626 /* This function is always called in a child shell
2627 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002628 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002629 unsigned sig;
2630 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002631
Denys Vlasenko67f71862009-09-25 14:21:06 +02002632 /* Child shells are not interactive.
2633 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2634 * Testcase: (while :; do :; done) + ^Z should background.
2635 * Same goes for SIGTERM, SIGHUP, SIGINT.
2636 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002637 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
Denys Vlasenko67f71862009-09-25 14:21:06 +02002638 return; /* already no traps and no SPECIAL_INTERACTIVE_SIGS */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002639
Denys Vlasenko67f71862009-09-25 14:21:06 +02002640 /* Switching off SPECIAL_INTERACTIVE_SIGS.
2641 * Stupid. It can be done with *single* &= op, but we can't use
2642 * the fact that G.blocked_set is implemented as a bitmask
2643 * in libc... */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002644 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2645 sig = 1;
2646 while (1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002647 if (mask & 1) {
2648 /* Careful. Only if no trap or trap is not "" */
2649 if (!G.traps || !G.traps[sig] || G.traps[sig][0])
2650 sigdelset(&G.blocked_set, sig);
2651 }
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002652 mask >>= 1;
2653 if (!mask)
2654 break;
2655 sig++;
2656 }
Denys Vlasenko67f71862009-09-25 14:21:06 +02002657 /* Our homegrown sig mask is saner to work with :) */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002658 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002659
2660 /* Resetting all traps to default except empty ones */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002661 mask = G.non_DFL_mask;
2662 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
Denys Vlasenko67f71862009-09-25 14:21:06 +02002663 if (!G.traps[sig] || !G.traps[sig][0])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002664 continue;
2665 free(G.traps[sig]);
2666 G.traps[sig] = NULL;
2667 /* There is no signal for 0 (EXIT) */
2668 if (sig == 0)
2669 continue;
Denys Vlasenko67f71862009-09-25 14:21:06 +02002670 /* There was a trap handler, we just removed it.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002671 * But if sig still has non-DFL handling,
Denys Vlasenko67f71862009-09-25 14:21:06 +02002672 * we should not unblock the sig. */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002673 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002674 continue;
2675 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002676 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002677 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002678}
2679
2680#else /* !BB_MMU */
2681
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002682static void re_execute_shell(char ***to_free, const char *s,
2683 char *g_argv0, char **g_argv,
2684 char **builtin_argv) NORETURN;
2685static void re_execute_shell(char ***to_free, const char *s,
2686 char *g_argv0, char **g_argv,
2687 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002688{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002689 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002690 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002691 struct variable *cur;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002692# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002693 struct function *funcp;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002694# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002695 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002696 unsigned cnt;
2697
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002698 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002699 argv = heredoc_argv;
2700 argv[0] = (char *) G.argv0_for_re_execing;
2701 argv[1] = (char *) "-<";
2702 argv[2] = (char *) s;
2703 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002704 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002705 goto do_exec;
2706 }
2707
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002708 cnt = 0;
2709 pp = builtin_argv;
2710 if (pp) while (*pp++)
2711 cnt++;
2712
Denys Vlasenkodea47882009-10-09 15:40:49 +02002713 sprintf(param_buf, "-$%x:%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002714 , (unsigned) G.root_pid
Denys Vlasenkodea47882009-10-09 15:40:49 +02002715 , (unsigned) G.root_ppid
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002716 , (unsigned) G.last_bg_pid
2717 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002718 , cnt
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002719 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002720 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002721 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002722 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002723 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002724 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002725 for (cur = G.top_var; cur; cur = cur->next) {
2726 if (!cur->flg_export || cur->flg_read_only)
2727 cnt += 2;
2728 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002729# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002730 for (funcp = G.top_func; funcp; funcp = funcp->next)
2731 cnt += 3;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002732# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002733 pp = g_argv;
2734 while (*pp++)
2735 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002736 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002737 *pp++ = (char *) G.argv0_for_re_execing;
2738 *pp++ = param_buf;
2739 for (cur = G.top_var; cur; cur = cur->next) {
2740 if (cur->varstr == hush_version_str)
2741 continue;
2742 if (cur->flg_read_only) {
2743 *pp++ = (char *) "-R";
2744 *pp++ = cur->varstr;
2745 } else if (!cur->flg_export) {
2746 *pp++ = (char *) "-V";
2747 *pp++ = cur->varstr;
2748 }
2749 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002750# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobc569742009-04-12 20:35:19 +00002751 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2752 *pp++ = (char *) "-F";
2753 *pp++ = funcp->name;
2754 *pp++ = funcp->body_as_string;
2755 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02002756# endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002757 /* We can pass activated traps here. Say, -Tnn:trap_string
2758 *
2759 * However, POSIX says that subshells reset signals with traps
2760 * to SIG_DFL.
2761 * I tested bash-3.2 and it not only does that with true subshells
2762 * of the form ( list ), but with any forked children shells.
2763 * I set trap "echo W" WINCH; and then tried:
2764 *
2765 * { echo 1; sleep 20; echo 2; } &
2766 * while true; do echo 1; sleep 20; echo 2; break; done &
2767 * true | { echo 1; sleep 20; echo 2; } | cat
2768 *
2769 * In all these cases sending SIGWINCH to the child shell
2770 * did not run the trap. If I add trap "echo V" WINCH;
2771 * _inside_ group (just before echo 1), it works.
2772 *
2773 * I conclude it means we don't need to pass active traps here.
2774 * exec syscall below resets them to SIG_DFL for us.
2775 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002776 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002777 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002778 if (builtin_argv) {
2779 while (*++builtin_argv)
2780 *pp++ = *builtin_argv;
2781 *pp++ = (char *) "";
2782 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002783 *pp++ = g_argv0;
2784 while (*g_argv)
2785 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002786 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002787 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002788
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002789 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002790 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2791 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002792 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002793 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002794 if (argv[0][0] == '/')
2795 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002796 xfunc_error_retval = 127;
2797 bb_error_msg_and_die("can't re-execute the shell");
2798}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002799#endif /* !BB_MMU */
2800
2801
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002802static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002803{
2804 struct fd_pair pair;
2805 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002806 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002807 /* the _body_ of heredoc (misleading field name) */
2808 const char *heredoc = redir->rd_filename;
2809 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002810#if !BB_MMU
2811 char **to_free;
2812#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002813
2814 expanded = NULL;
2815 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2816 expanded = expand_pseudo_dquoted(heredoc);
2817 if (expanded)
2818 heredoc = expanded;
2819 }
2820 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002821
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002822 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002823 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002824 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002825
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002826 /* Try writing without forking. Newer kernels have
2827 * dynamically growing pipes. Must use non-blocking write! */
2828 ndelay_on(pair.wr);
2829 while (1) {
2830 written = write(pair.wr, heredoc, len);
2831 if (written <= 0)
2832 break;
2833 len -= written;
2834 if (len == 0) {
2835 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002836 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002837 return;
2838 }
2839 heredoc += written;
2840 }
2841 ndelay_off(pair.wr);
2842
2843 /* Okay, pipe buffer was not big enough */
2844 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002845 * for the unsuspecting parent process. Child creates a grandchild
2846 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002847 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002848#if !BB_MMU
2849 to_free = NULL;
2850#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002851 pid = vfork();
2852 if (pid < 0)
2853 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002854 if (pid == 0) {
2855 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002856 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002857 pid = BB_MMU ? fork() : vfork();
2858 if (pid < 0)
2859 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2860 if (pid != 0)
2861 _exit(0);
2862 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002863 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002864#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002865 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002866 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002867#else
2868 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002869 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002870 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002871#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002872 }
2873 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02002874#if ENABLE_HUSH_FAST
2875 G.count_SIGCHLD++;
2876//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2877#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002878 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002879#if !BB_MMU
2880 free(to_free);
2881#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002882 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002883 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002884 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002885}
2886
Eric Andersen25f27032001-04-26 23:22:31 +00002887/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2888 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002889static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002890{
2891 int openfd, mode;
2892 struct redir_struct *redir;
2893
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002894 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002895 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002896 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002897 if (squirrel && redir->rd_fd < 3
2898 && squirrel[redir->rd_fd] < 0
2899 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002900 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002901 }
2902 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2903 * of the heredoc */
2904 debug_printf_parse("set heredoc '%s'\n",
2905 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002906 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002907 continue;
2908 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002909
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002910 if (redir->rd_dup == REDIRFD_TO_FILE) {
2911 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002912 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002913 if (redir->rd_filename == NULL) {
2914 /* Something went wrong in the parse.
2915 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002916 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002917 continue;
2918 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002919 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002920 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002921 openfd = open_or_warn(p, mode);
2922 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002923 if (openfd < 0) {
2924 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002925 * bash and ash both lose it as well (though zsh doesn't!) */
2926//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002927 return 1;
2928 }
2929 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002930 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002931 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002932 }
2933
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002934 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002935 if (squirrel && redir->rd_fd < 3
2936 && squirrel[redir->rd_fd] < 0
2937 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002938 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002939 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002940 if (openfd == REDIRFD_CLOSE) {
2941 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002942 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002943 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002944 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002945 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002946 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002947 }
Eric Andersen25f27032001-04-26 23:22:31 +00002948 }
2949 }
2950 return 0;
2951}
2952
2953static void restore_redirects(int squirrel[])
2954{
2955 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002956 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002957 fd = squirrel[i];
2958 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002959 /* We simply die on error */
2960 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002961 }
2962 }
2963}
2964
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002965
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002966static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002967
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002968/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002969static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002970{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002971 char **p;
2972 struct command *command;
2973 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002974 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002975
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002976 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002977 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002978 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002979 for (i = 0; i < pi->num_cmds; i++) {
2980 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002981 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002982 if (command->argv) {
2983 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002984 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985 }
2986 free_strings(command->argv);
2987 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002988 }
2989 /* not "else if": on syntax error, we may have both! */
2990 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002991 debug_printf_clean(" begin group (cmd_type:%d)\n",
2992 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002993 free_pipe_list(command->group);
2994 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002995 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002997 /* else is crucial here.
2998 * If group != NULL, child_func is meaningless */
2999#if ENABLE_HUSH_FUNCTIONS
3000 else if (command->child_func) {
3001 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
3002 command->child_func->parent_cmd = NULL;
3003 }
3004#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003005#if !BB_MMU
3006 free(command->group_as_string);
3007 command->group_as_string = NULL;
3008#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003009 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003010 debug_printf_clean(" redirect %d%s",
3011 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003012 /* guard against the case >$FOO, where foo is unset or blank */
3013 if (r->rd_filename) {
3014 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
3015 free(r->rd_filename);
3016 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003017 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003018 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003019 rnext = r->next;
3020 free(r);
3021 }
3022 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003023 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003024 free(pi->cmds); /* children are an array, they get freed all at once */
3025 pi->cmds = NULL;
3026#if ENABLE_HUSH_JOB
3027 free(pi->cmdtext);
3028 pi->cmdtext = NULL;
3029#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003030}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003031
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003032static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003033{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003034 struct pipe *pi, *next;
3035
3036 for (pi = head; pi; pi = next) {
3037#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003038 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003039#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003040 free_pipe(pi);
3041 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003042 next = pi->next;
3043 /*pi->next = NULL;*/
3044 free(pi);
3045 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003046}
3047
3048
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003049static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003050#if BB_MMU
3051#define parse_stream(pstring, input, end_trigger) \
3052 parse_stream(input, end_trigger)
3053#endif
3054static struct pipe *parse_stream(char **pstring,
3055 struct in_str *input,
3056 int end_trigger);
3057static void parse_and_run_string(const char *s);
3058
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003059
Mike Frysinger93cadc22009-05-27 17:06:25 -04003060static char *find_in_path(const char *arg)
3061{
3062 char *ret = NULL;
3063 const char *PATH = get_local_var_value("PATH");
3064
3065 if (!PATH)
3066 return NULL;
3067
3068 while (1) {
3069 const char *end = strchrnul(PATH, ':');
3070 int sz = end - PATH; /* must be int! */
3071
3072 free(ret);
3073 if (sz != 0) {
3074 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3075 } else {
3076 /* We have xxx::yyyy in $PATH,
3077 * it means "use current dir" */
3078 ret = xstrdup(arg);
3079 }
3080 if (access(ret, F_OK) == 0)
3081 break;
3082
3083 if (*end == '\0') {
3084 free(ret);
3085 return NULL;
3086 }
3087 PATH = end + 1;
3088 }
3089
3090 return ret;
3091}
3092
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003093static const struct built_in_command* find_builtin_helper(const char *name,
3094 const struct built_in_command *x,
3095 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003096{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003097 while (x != end) {
3098 if (strcmp(name, x->cmd) != 0) {
3099 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003100 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003101 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003102 debug_printf_exec("found builtin '%s'\n", name);
3103 return x;
3104 }
3105 return NULL;
3106}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003107static const struct built_in_command* find_builtin1(const char *name)
3108{
3109 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3110}
3111static const struct built_in_command* find_builtin(const char *name)
3112{
3113 const struct built_in_command *x = find_builtin1(name);
3114 if (x)
3115 return x;
3116 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3117}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003118
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003119#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003120static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003121{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003122 struct function **funcpp = &G.top_func;
3123 while (*funcpp) {
3124 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003125 break;
3126 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003127 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003128 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003129 return funcpp;
3130}
3131
3132static const struct function *find_function(const char *name)
3133{
3134 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003135 if (funcp)
3136 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003137 return funcp;
3138}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003139
Denis Vlasenkobc569742009-04-12 20:35:19 +00003140/* Note: takes ownership on name ptr */
3141static struct function *new_function(char *name)
3142{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003143 struct function **funcpp = find_function_slot(name);
3144 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003145
Denys Vlasenko873273d2009-09-12 14:47:41 +02003146 if (funcp != NULL) {
3147 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003148 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3149 if (!cmd) {
3150 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3151 free(funcp->name);
3152 /* Note: if !funcp->body, do not free body_as_string!
3153 * This is a special case of "-F name body" function:
3154 * body_as_string was not malloced! */
3155 if (funcp->body) {
3156 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003157# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003158 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003159# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003160 }
3161 } else {
3162 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3163 cmd->argv[0] = funcp->name;
3164 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003165# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003166 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003167# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003168 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003169 } else {
3170 debug_printf_exec("remembering new function '%s'\n", name);
3171 funcp = *funcpp = xzalloc(sizeof(*funcp));
3172 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003173 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003174
Denis Vlasenkobc569742009-04-12 20:35:19 +00003175 funcp->name = name;
3176 return funcp;
3177}
3178
Denis Vlasenko40e84372009-04-18 11:23:38 +00003179static void unset_func(const char *name)
3180{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003181 struct function **funcpp = find_function_slot(name);
3182 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003183
Denys Vlasenko873273d2009-09-12 14:47:41 +02003184 if (funcp != NULL) {
3185 debug_printf_exec("freeing function '%s'\n", funcp->name);
3186 *funcpp = funcp->next;
3187 /* funcp is unlinked now, deleting it.
3188 * Note: if !funcp->body, the function was created by
3189 * "-F name body", do not free ->body_as_string
3190 * and ->name as they were not malloced. */
3191 if (funcp->body) {
3192 free_pipe_list(funcp->body);
3193 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003194# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003195 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003196# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003197 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003198 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003199 }
3200}
3201
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003202# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003203#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003204 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003205# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003206static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003207 const struct function *funcp,
3208 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003209static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003210 const struct function *funcp,
3211 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003212{
3213# if BB_MMU
3214 int n = 1;
3215
3216 argv[0] = G.global_argv[0];
3217 G.global_argv = argv;
3218 while (*++argv)
3219 n++;
3220 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003221 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003222 n = run_list(funcp->body);
3223 fflush(NULL);
3224 _exit(n);
3225# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003226 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003227 funcp->body_as_string,
3228 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003229 argv + 1,
3230 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003231# endif
3232}
3233
3234static int run_function(const struct function *funcp, char **argv)
3235{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003236 int rc;
3237 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003238 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003239
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003240 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003241
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003242 /* "we are in function, ok to use return" */
3243 sv_flg = G.flag_return_in_progress;
3244 G.flag_return_in_progress = -1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003245# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003246 G.func_nest_level++;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003247# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003248
Denis Vlasenkobc569742009-04-12 20:35:19 +00003249 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003250# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003251 if (!funcp->body) {
3252 /* Function defined by -F */
3253 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003254 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003255 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003256# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003257 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003258 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003259 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003260
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003261# if ENABLE_HUSH_LOCAL
Denys Vlasenko295fef82009-06-03 12:47:26 +02003262 {
3263 struct variable *var;
3264 struct variable **var_pp;
3265
3266 var_pp = &G.top_var;
3267 while ((var = *var_pp) != NULL) {
3268 if (var->func_nest_level < G.func_nest_level) {
3269 var_pp = &var->next;
3270 continue;
3271 }
3272 /* Unexport */
3273 if (var->flg_export)
3274 bb_unsetenv(var->varstr);
3275 /* Remove from global list */
3276 *var_pp = var->next;
3277 /* Free */
3278 if (!var->max_len)
3279 free(var->varstr);
3280 free(var);
3281 }
3282 G.func_nest_level--;
3283 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003284# endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003285 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003286
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003287 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003288
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003289 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003290}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003291#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003292
3293
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003294#if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003295#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003296 exec_builtin(x, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003297#else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003298#define exec_builtin(to_free, x, argv) \
3299 exec_builtin(to_free, argv)
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003300#endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003301static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003302 const struct built_in_command *x,
3303 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003304static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003305 const struct built_in_command *x,
3306 char **argv)
3307{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003308#if BB_MMU
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003309 int rcode = x->function(argv);
3310 fflush(NULL);
3311 _exit(rcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003312#else
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003313 /* On NOMMU, we must never block!
3314 * Example: { sleep 99 | read line; } & echo Ok
3315 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003316 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003317 argv[0],
3318 G.global_argv[0],
3319 G.global_argv + 1,
3320 argv);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02003321#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003322}
3323
3324
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003325#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003326#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3327 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3328#define pseudo_exec(nommu_save, command, argv_expanded) \
3329 pseudo_exec(command, argv_expanded)
3330#endif
3331
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003332/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003333 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003334 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003335 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003336 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003337static void pseudo_exec_argv(nommu_save_t *nommu_save,
3338 char **argv, int assignment_cnt,
3339 char **argv_expanded) NORETURN;
3340static void pseudo_exec_argv(nommu_save_t *nommu_save,
3341 char **argv, int assignment_cnt,
3342 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003343{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003344 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003345
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003346 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003347 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003348 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003349
Denis Vlasenko9504e442008-10-29 01:19:15 +00003350 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003351#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003352 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003353 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003354 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003355 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003356#else
3357 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003358 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003359#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003360 if (argv_expanded) {
3361 argv = argv_expanded;
3362 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003363 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003364#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003365 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003366#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003367 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003368
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003369#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3370 if (strchr(argv[0], '/') != NULL)
3371 goto skip;
3372#endif
3373
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003374 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003375 * Depending on context, this might be redundant. But it's
3376 * easier to waste a few CPU cycles than it is to figure out
3377 * if this is one of those cases.
3378 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003379 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003380 /* On NOMMU, it is more expensive to re-execute shell
3381 * just in order to run echo or test builtin.
3382 * It's better to skip it here and run corresponding
3383 * non-builtin later. */
3384 const struct built_in_command *x;
3385 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003386 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003387 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003388 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003389 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003390#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003391 /* Check if the command matches any functions */
3392 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003393 const struct function *funcp = find_function(argv[0]);
3394 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003395 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003396 }
3397 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003398#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003399
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003400#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003401 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003402 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003403 int a = find_applet_by_name(argv[0]);
3404 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003405# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003406 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003407 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003408 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003409 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003410# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003411 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003412 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003413 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3414 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003415 /* If they called chroot or otherwise made the binary no longer
3416 * executable, fall through */
3417 }
3418 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003419#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003420
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003421#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003422 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003423#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003424 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003425 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003426 execvp(argv[0], argv);
Denis Vlasenkof9d4fc32009-04-21 20:40:51 +00003427 bb_perror_msg("can't execute '%s'", argv[0]);
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003428 _exit(127); /* bash compat */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003429}
3430
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003431/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003432 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003433static void pseudo_exec(nommu_save_t *nommu_save,
3434 struct command *command,
3435 char **argv_expanded) NORETURN;
3436static void pseudo_exec(nommu_save_t *nommu_save,
3437 struct command *command,
3438 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003439{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003440 if (command->argv) {
3441 pseudo_exec_argv(nommu_save, command->argv,
3442 command->assignment_cnt, argv_expanded);
3443 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003444
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003445 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003446 /* Cases when we are here:
3447 * ( list )
3448 * { list } &
3449 * ... | ( list ) | ...
3450 * ... | { list } | ...
3451 */
3452#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003453 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003454 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003455 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003456 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003457 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003458 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003459 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003460#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003461 re_execute_shell(&nommu_save->argv_from_re_execing,
3462 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003463 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003464 G.global_argv + 1,
3465 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003466#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003467 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003468
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003469 /* Case when we are here: ... | >file */
3470 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003471 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003472}
3473
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003474#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003475static const char *get_cmdtext(struct pipe *pi)
3476{
3477 char **argv;
3478 char *p;
3479 int len;
3480
3481 /* This is subtle. ->cmdtext is created only on first backgrounding.
3482 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003483 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003484 if (pi->cmdtext)
3485 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003486 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003487 if (!argv || !argv[0]) {
3488 pi->cmdtext = xzalloc(1);
3489 return pi->cmdtext;
3490 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003491
3492 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003493 do {
3494 len += strlen(*argv) + 1;
3495 } while (*++argv);
3496 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003497 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003498 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003499 do {
3500 len = strlen(*argv);
3501 memcpy(p, *argv, len);
3502 p += len;
3503 *p++ = ' ';
3504 } while (*++argv);
3505 p[-1] = '\0';
3506 return pi->cmdtext;
3507}
3508
Eric Andersenbafd94f2001-05-02 16:11:59 +00003509static void insert_bg_job(struct pipe *pi)
3510{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003511 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003512 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003513
3514 /* Linear search for the ID of the job to use */
3515 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003516 for (job = G.job_list; job; job = job->next)
3517 if (job->jobid >= pi->jobid)
3518 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003519
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003520 /* Add job to the list of running jobs */
3521 jobp = &G.job_list;
3522 while ((job = *jobp) != NULL)
3523 jobp = &job->next;
3524 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003525
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003526 *job = *pi; /* physical copy */
3527 job->next = NULL;
3528 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3529 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003530 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003531 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003532 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003533 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003534 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003535
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003536 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003537 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3538 /* Last command's pid goes to $! */
3539 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3540 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003541}
3542
Eric Andersenbafd94f2001-05-02 16:11:59 +00003543static void remove_bg_job(struct pipe *pi)
3544{
3545 struct pipe *prev_pipe;
3546
Denis Vlasenko87a86552008-07-29 19:43:10 +00003547 if (pi == G.job_list) {
3548 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003549 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003550 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003551 while (prev_pipe->next != pi)
3552 prev_pipe = prev_pipe->next;
3553 prev_pipe->next = pi->next;
3554 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003555 if (G.job_list)
3556 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003557 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003558 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003559}
Eric Andersen028b65b2001-06-28 01:10:11 +00003560
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003561/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003562static void delete_finished_bg_job(struct pipe *pi)
3563{
3564 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003565 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003566 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003567 free(pi);
3568}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003569#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003570
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003571/* Check to see if any processes have exited -- if they
3572 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003573static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003574{
Eric Andersenc798b072001-06-22 06:23:03 +00003575 int attributes;
3576 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003577#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003578 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003579#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003580 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003581 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003582
Denis Vlasenkod5762932009-03-31 11:22:57 +00003583 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3584
Eric Andersenc798b072001-06-22 06:23:03 +00003585 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003586 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003587 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003588
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003589 errno = 0;
3590#if ENABLE_HUSH_FAST
3591 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3592//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3593//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003594 /* There was neither fork nor SIGCHLD since last waitpid */
3595 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003596 if (!G.we_have_children) {
3597 errno = ECHILD;
3598 return -1;
3599 }
3600 if (fg_pipe == NULL) { /* is WNOHANG set? */
3601 /* We have children, but they did not exit
3602 * or stop yet (we saw no SIGCHLD) */
3603 return 0;
3604 }
3605 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3606 }
3607#endif
3608
Denis Vlasenko1359da62007-04-21 23:27:30 +00003609/* Do we do this right?
3610 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003611 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003612 * [3]+ Stopped sleep 20 | false
3613 * bash-3.00# echo $?
3614 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003615 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003616 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003617 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003618 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003619 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003620 int dead;
3621
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003622#if ENABLE_HUSH_FAST
3623 i = G.count_SIGCHLD;
3624#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003625 childpid = waitpid(-1, &status, attributes);
3626 if (childpid <= 0) {
3627 if (childpid && errno != ECHILD)
3628 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003629#if ENABLE_HUSH_FAST
3630 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003631 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003632 G.handled_SIGCHLD = i;
3633//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3634 }
3635#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003636 break;
3637 }
3638 dead = WIFEXITED(status) || WIFSIGNALED(status);
3639
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003640#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003641 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003642 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003643 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3644 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003645 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003646 childpid, WTERMSIG(status), WEXITSTATUS(status));
3647 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003648 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003649 childpid, WEXITSTATUS(status));
3650#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003651 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003652 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003653 for (i = 0; i < fg_pipe->num_cmds; i++) {
3654 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3655 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003656 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003657 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003658 fg_pipe->cmds[i].pid = 0;
3659 fg_pipe->alive_cmds--;
3660 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003661 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003662 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003663 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003664 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003665 /* bash prints killer signal's name for *last*
Denis Vlasenko40e84372009-04-18 11:23:38 +00003666 * process in pipe (prints just newline for SIGINT).
Denys Vlasenko4ea0ca82009-09-25 12:58:37 +02003667 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003668 */
3669 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003670 int sig = WTERMSIG(status);
3671 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003672 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003673 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003674 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003675 fg_pipe->cmds[i].is_stopped = 1;
3676 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003677 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003678 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3679 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3680 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003681 /* All processes in fg pipe have exited or stopped */
3682/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3683 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3684 * and "killall -STOP cat" */
3685 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003686#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003687 if (fg_pipe->alive_cmds)
3688 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003689#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003690 return rcode;
3691 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02003692 if (!fg_pipe->alive_cmds)
3693 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003694 }
3695 /* There are still running processes in the fg pipe */
3696 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003697 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003698 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003699 }
3700
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003701#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003702 /* We asked to wait for bg or orphaned children */
3703 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003704 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003705 for (i = 0; i < pi->num_cmds; i++) {
3706 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003707 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003708 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003709 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003710 /* Happens when shell is used as init process (init=/bin/sh) */
3711 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003712 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003713
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003714 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003715 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003716 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003717 pi->cmds[i].pid = 0;
3718 pi->alive_cmds--;
3719 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003720 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003721 printf(JOB_STATUS_FORMAT, pi->jobid,
3722 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003723 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003724 }
3725 } else {
3726 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003727 pi->cmds[i].is_stopped = 1;
3728 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003729 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003730#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003731 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003732
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003733 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003734}
3735
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003736#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003737static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3738{
3739 pid_t p;
3740 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003741 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003742 /* Job finished, move the shell to the foreground */
3743 p = getpgrp(); /* our process group id */
3744 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3745 tcsetpgrp(G_interactive_fd, p);
3746 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003747 return rcode;
3748}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003749#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003750
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003751/* Start all the jobs, but don't wait for anything to finish.
3752 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003753 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003754 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003755 * to finish to determine the exit status of the pipe. If the pipe
3756 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003757 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003758 * return value.
3759 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003760 * Returns -1 only if started some children. IOW: we have to
3761 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003762 *
3763 * The only case when we do not need to [v]fork is when the pipe
3764 * is single, non-backgrounded, non-subshell command. Examples:
3765 * cmd ; ... { list } ; ...
3766 * cmd && ... { list } && ...
3767 * cmd || ... { list } || ...
3768 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3769 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003770 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003771 *
3772 * Cases when we must fork:
3773 * non-single: cmd | cmd
3774 * backgrounded: cmd & { list } &
3775 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003776 */
Denys Vlasenkoa7bb3c12009-10-08 12:28:08 +02003777static NOINLINE int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003778{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003779 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003780 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003781 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003782 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003783 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003784 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003785 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003786 /* it is not always needed, but we aim to smaller code */
3787 int squirrel[] = { -1, -1, -1 };
3788 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003789
Denis Vlasenko552433b2009-04-04 19:29:21 +00003790 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003791 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003792
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003793 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003794 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003795 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003796 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003797
Denis Vlasenko552433b2009-04-04 19:29:21 +00003798 if (pi->num_cmds != 1
3799 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003800 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00003801 ) {
3802 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003803 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003804
Denis Vlasenko552433b2009-04-04 19:29:21 +00003805 pi->alive_cmds = 1;
3806
3807 debug_printf_exec(": group:%p argv:'%s'\n",
3808 command->group, command->argv ? command->argv[0] : "NONE");
3809
3810 if (command->group) {
3811#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003812 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003813 /* "executing" func () { list } */
3814 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003815
Denis Vlasenkobc569742009-04-12 20:35:19 +00003816 funcp = new_function(command->argv[0]);
3817 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003818 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003819# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003820 funcp->body_as_string = command->group_as_string;
3821 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003822# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003823 command->group = NULL;
3824 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003825 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3826 funcp->parent_cmd = command;
3827 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003828
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003829 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3830 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003831 return EXIT_SUCCESS;
3832 }
3833#endif
3834 /* { list } */
3835 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003836 rcode = 1; /* exitcode if redir failed */
3837 if (setup_redirects(command, squirrel) == 0) {
3838 debug_printf_exec(": run_list\n");
3839 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003840 }
Eric Andersen04407e52001-06-07 16:42:05 +00003841 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003842 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003843 debug_leave();
3844 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003845 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003846 }
3847
Denis Vlasenko552433b2009-04-04 19:29:21 +00003848 argv = command->argv ? command->argv : (char **) &null_ptr;
3849 {
3850 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003851#if ENABLE_HUSH_FUNCTIONS
3852 const struct function *funcp;
3853#else
3854 enum { funcp = 0 };
3855#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003856 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003857 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003858
Denis Vlasenko552433b2009-04-04 19:29:21 +00003859 if (argv[command->assignment_cnt] == NULL) {
3860 /* Assignments, but no command */
3861 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003862 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003863 restore_redirects(squirrel);
3864 /* Set shell variables */
3865 while (*argv) {
3866 p = expand_string_to_string(*argv);
3867 debug_printf_exec("set shell var:'%s'->'%s'\n",
3868 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003869 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003870 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003871 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003872 /* Do we need to flag set_local_var() errors?
3873 * "assignment to readonly var" and "putenv error"
3874 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003875 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003876 debug_leave();
3877 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003878 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003879 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003880
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003881 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003882 if (0) {}
3883#if ENABLE_HUSH_BASH_COMPAT
3884 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003885 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3886 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003887#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003888#ifdef CMD_SINGLEWORD_NOGLOB_COND
3889 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3890 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3891
3892 }
3893#endif
3894 else {
3895 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3896 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003897
Denys Vlasenkof37eb392009-10-18 11:46:35 +02003898 /* if someone gives us an empty string: `cmd with empty output` */
Mike Frysinger28736c32009-10-18 01:11:45 -04003899 if (!argv_expanded[0]) {
3900 debug_leave();
3901 return 0;
3902 }
3903
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003904 x = find_builtin(argv_expanded[0]);
3905#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003906 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003907 if (!x)
3908 funcp = find_function(argv_expanded[0]);
3909#endif
3910 if (x || funcp) {
3911 if (!funcp) {
3912 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3913 debug_printf("exec with redirects only\n");
3914 rcode = setup_redirects(command, NULL);
3915 goto clean_up_and_ret1;
3916 }
Eric Andersen25f27032001-04-26 23:22:31 +00003917 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003918 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003919 * This is perfect for work that comes after exec().
3920 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003921 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003922 rcode = setup_redirects(command, squirrel);
3923 if (rcode == 0) {
3924 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003925 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003926 if (!funcp) {
3927 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003928 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003929 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003930 fflush(NULL);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003931 }
3932#if ENABLE_HUSH_FUNCTIONS
3933 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02003934# if ENABLE_HUSH_LOCAL
3935 struct variable **sv;
3936 sv = G.shadowed_vars_pp;
3937 G.shadowed_vars_pp = &old_vars;
3938# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003939 debug_printf_exec(": function '%s' '%s'...\n",
3940 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003941 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003942# if ENABLE_HUSH_LOCAL
3943 G.shadowed_vars_pp = sv;
3944# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003945 }
3946#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003947 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003948#if ENABLE_FEATURE_SH_STANDALONE
3949 clean_up_and_ret:
3950#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003951 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003952 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003953 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003954 clean_up_and_ret1:
3955 free(argv_expanded);
3956 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003957 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003958 debug_printf_exec("run_pipe return %d\n", rcode);
3959 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003960 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003961
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003962#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003963 i = find_applet_by_name(argv_expanded[0]);
3964 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003965 rcode = setup_redirects(command, squirrel);
3966 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003967 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003968 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003969 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003970 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003971 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003972 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003973 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003974 }
3975#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003976 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003977 }
3978
Denis Vlasenko552433b2009-04-04 19:29:21 +00003979 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003980 /* NB: argv_expanded may already be created, and that
3981 * might include `cmd` runs! Do not rerun it! We *must*
3982 * use argv_expanded if it's non-NULL */
3983
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003984 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003985 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003986 nextin = 0;
3987
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003988 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003989 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003990#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003991 volatile nommu_save_t nommu_save;
3992 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003993 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003994 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003995 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003996#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003997 command = &(pi->cmds[i]);
3998 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003999 debug_printf_exec(": pipe member '%s' '%s'...\n",
4000 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00004001 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004002 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00004003 }
Eric Andersen25f27032001-04-26 23:22:31 +00004004
4005 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004006 pipefds.rd = 0;
4007 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004008 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004009 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00004010
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004011 command->pid = BB_MMU ? fork() : vfork();
4012 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004013#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004014 disable_restore_tty_pgrp_on_exit();
Denys Vlasenko76ace252009-10-12 15:25:01 +02004015 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004016
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004017 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00004018 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004019 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00004020 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004021 pgrp = pi->pgrp;
4022 if (pgrp < 0) /* true for 1st process only */
4023 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004024 if (setpgid(0, pgrp) == 0
4025 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04004026 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00004027 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004028 /* We do it in *every* child, not just first,
4029 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004030 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004031 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004032 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004033#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004034 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
4035 /* 1st cmd in backgrounded pipe
4036 * should have its stdin /dev/null'ed */
4037 close(0);
4038 if (open(bb_dev_null, O_RDONLY))
4039 xopen("/", O_RDONLY);
4040 } else {
4041 xmove_fd(nextin, 0);
4042 }
4043 xmove_fd(pipefds.wr, 1);
4044 if (pipefds.rd > 1)
4045 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004046 /* Like bash, explicit redirects override pipes,
4047 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004048 if (setup_redirects(command, NULL))
4049 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004050
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004051 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004052 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4053
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004054 /* Stores to nommu_save list of env vars putenv'ed
4055 * (NOMMU, on MMU we don't need that) */
4056 /* cast away volatility... */
4057 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004058 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004059 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004060
Denis Vlasenkof9375282009-04-05 19:13:39 +00004061 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004062#if ENABLE_HUSH_FAST
4063 G.count_SIGCHLD++;
4064//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4065#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004066 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004067#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004068 /* Clean up after vforked child */
4069 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004070 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004071 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004072 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004073#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004074 free(argv_expanded);
4075 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004076 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004077 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004078 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004079 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004080 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004081#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004082 /* Second and next children need to know pid of first one */
4083 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004084 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004085#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004086 }
Eric Andersen25f27032001-04-26 23:22:31 +00004087
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004088 if (i)
4089 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004090 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004091 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004092 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004093 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004094 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004095
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004096 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004097 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004098 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4099 return 1;
4100 }
4101
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004102 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004103 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004104 return -1;
4105}
4106
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004107#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004108static void debug_print_tree(struct pipe *pi, int lvl)
4109{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004110 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004111 [PIPE_SEQ] = "SEQ",
4112 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004113 [PIPE_OR ] = "OR" ,
4114 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004115 };
4116 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004117 [RES_NONE ] = "NONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004118# if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004119 [RES_IF ] = "IF" ,
4120 [RES_THEN ] = "THEN" ,
4121 [RES_ELIF ] = "ELIF" ,
4122 [RES_ELSE ] = "ELSE" ,
4123 [RES_FI ] = "FI" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004124# endif
4125# if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004126 [RES_FOR ] = "FOR" ,
4127 [RES_WHILE] = "WHILE",
4128 [RES_UNTIL] = "UNTIL",
4129 [RES_DO ] = "DO" ,
4130 [RES_DONE ] = "DONE" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004131# endif
4132# if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004133 [RES_IN ] = "IN" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004134# endif
4135# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004136 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004137 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004138 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004139 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004140 [RES_ESAC ] = "ESAC" ,
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004141# endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004142 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004143 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004144 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004145 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004146 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004147 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004148 "[noglob]",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004149# if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004150 "func()",
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004151# endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004152 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004153
4154 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004155
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004156 pin = 0;
4157 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004158 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4159 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004160 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004161 while (prn < pi->num_cmds) {
4162 struct command *command = &pi->cmds[prn];
4163 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004164
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004165 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004166 lvl*2, "", prn,
4167 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004168 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004169 fprintf(stderr, " group %s: (argv=%p)\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004170 CMDTYPE[command->cmd_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004171 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004172 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004173 prn++;
4174 continue;
4175 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004176 if (argv) while (*argv) {
4177 fprintf(stderr, " '%s'", *argv);
4178 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004179 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004180 fprintf(stderr, "\n");
4181 prn++;
4182 }
4183 pi = pi->next;
4184 pin++;
4185 }
4186}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004187#endif /* debug_print_tree */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004188
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004189/* NB: called by pseudo_exec, and therefore must not modify any
4190 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004191static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004192{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004193#if ENABLE_HUSH_CASE
4194 char *case_word = NULL;
4195#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004196#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004197 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004198 char **for_lcur = NULL;
4199 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004200#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004201 smallint last_followup;
4202 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004203#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004204 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004205#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004206 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004207#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004208#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004209 smallint rword; /* enum reserved_style */
4210 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004211#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004212
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004213 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004214 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004215
Denis Vlasenko06810332007-05-21 23:30:54 +00004216#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004217 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004218 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4219 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004220 continue;
4221 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004222 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004223 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004224 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004225 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004226 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004227 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004228 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004229 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004230 continue;
4231 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004232 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4233 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004234 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004235 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004236 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004237 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004238 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004239 }
4240 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004241#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004242
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004243 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004244 * in order to return, no direct "return" statements please.
4245 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004246
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004247#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004248 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004249#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004250
Denis Vlasenko0e151382009-04-06 18:40:31 +00004251#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004252 rword = RES_NONE;
4253 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004254#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004255 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004256 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004257
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004258 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004259 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004260 if (G.flag_SIGINT)
4261 break;
4262
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004263 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004264 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4265 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004266#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004267 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004268 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004269 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004270 /* start of a loop: remember where loop starts */
4271 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004272 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004273 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004274#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004275 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004276 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004277 if ((rcode == 0 && last_followup == PIPE_OR)
4278 || (rcode != 0 && last_followup == PIPE_AND)
4279 ) {
4280 /* It is "<true> || CMD" or "<false> && CMD"
4281 * and we should not execute CMD */
4282 debug_printf_exec("skipped cmd because of || or &&\n");
4283 last_followup = pi->followup;
4284 continue;
4285 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004286 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004287 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004288 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004289#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004290 if (cond_code) {
4291 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004292 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004293 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004294 /* "if <false> THEN cmd": skip cmd */
4295 continue;
4296 }
4297 } else {
4298 if (rword == RES_ELSE || rword == RES_ELIF) {
4299 /* "if <true> then ... ELSE/ELIF cmd":
4300 * skip cmd and all following ones */
4301 break;
4302 }
4303 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004304#endif
4305#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004306 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004307 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004308 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004309
4310 static const char encoded_dollar_at[] ALIGN1 = {
4311 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4312 }; /* encoded representation of "$@" */
4313 static const char *const encoded_dollar_at_argv[] = {
4314 encoded_dollar_at, NULL
4315 }; /* argv list with one element: "$@" */
4316 char **vals;
4317
4318 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004319 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004320 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004321 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004322 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004323 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004324 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004325 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004326 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004327 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004328 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004329 debug_print_strings("for_list made from", vals);
4330 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004331 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004332 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004333 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004334 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004335 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004336 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004337 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004338 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004339 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004340 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004341 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004342 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004343 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 +02004344 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004345 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004346 if (rword == RES_IN) {
4347 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4348 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004349 if (rword == RES_DONE) {
4350 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004351 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004352#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004353#if ENABLE_HUSH_CASE
4354 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004355 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004356 continue;
4357 }
4358 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004359 char **argv;
4360
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004361 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4362 break;
4363 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004364 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004365 while (*argv) {
4366 char *pattern = expand_string_to_string(*argv);
4367 /* TODO: which FNM_xxx flags to use? */
4368 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4369 free(pattern);
4370 if (cond_code == 0) { /* match! we will execute this branch */
4371 free(case_word); /* make future "word)" stop */
4372 case_word = NULL;
4373 break;
4374 }
4375 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004376 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004377 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004378 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004379 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004380 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004381 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004382 }
4383#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004384 /* Just pressing <enter> in shell should check for jobs.
4385 * OTOH, in non-interactive shell this is useless
4386 * and only leads to extra job checks */
4387 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004388 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004389 goto check_jobs_and_continue;
4390 continue;
4391 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004392
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004393 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004394 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004395 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004396 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004397 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004398 {
4399 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004400#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004401 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004402#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004403 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4404 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004405 /* We ran a builtin, function, or group.
4406 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004407 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004408 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004409 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004410 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004411#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004412 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004413 if (G.flag_break_continue) {
4414 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004415 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004416 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004417 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004418 G.depth_break_continue--;
4419 if (G.depth_break_continue == 0)
4420 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004421 /* else: e.g. "continue 2" should *break* once, *then* continue */
4422 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004423 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004424 goto check_jobs_and_break;
4425 /* "continue": simulate end of loop */
4426 rword = RES_DONE;
4427 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004428 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004429#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004430#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004431 if (G.flag_return_in_progress == 1) {
4432 /* same as "goto check_jobs_and_break" */
4433 checkjobs(NULL);
4434 break;
4435 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004436#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004437 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004438 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004439 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004440 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4441 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004442 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004443#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004444 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004445 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004446#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004447 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004448 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004449 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004450#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004451 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004452 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004453 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004454 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004455 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004456 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004457#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004458 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004459 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004460 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004461 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004462 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004463 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004464 }
4465 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004466
4467 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004468#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004469 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004470 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004471#endif
4472#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004473 /* Beware of "while false; true; do ..."! */
4474 if (pi->next && pi->next->res_word == RES_DO) {
4475 if (rword == RES_WHILE) {
4476 if (rcode) {
4477 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004478 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004479 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4480 goto check_jobs_and_break;
4481 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004482 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004483 if (rword == RES_UNTIL) {
4484 if (!rcode) {
4485 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004486 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004487 checkjobs(NULL);
4488 break;
4489 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004490 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004491 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004492#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004493
4494 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004495 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004496 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004497
4498#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004499 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004500#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004501#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004502 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004503 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004504 free(for_list);
4505#endif
4506#if ENABLE_HUSH_CASE
4507 free(case_word);
4508#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004509 debug_leave();
4510 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004511 return rcode;
4512}
4513
Eric Andersen25f27032001-04-26 23:22:31 +00004514/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004515static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004516{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004517 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004518 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004519 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004520 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004521 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004522 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004523 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004524 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004525 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004526 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004527 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004528 return rcode;
4529}
4530
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004531
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004532static struct pipe *new_pipe(void)
4533{
Eric Andersen25f27032001-04-26 23:22:31 +00004534 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004535 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004536 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004537 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004538 return pi;
4539}
4540
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004541/* Command (member of a pipe) is complete, or we start a new pipe
4542 * if ctx->command is NULL.
4543 * No errors possible here.
4544 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004545static int done_command(struct parse_context *ctx)
4546{
4547 /* The command is really already in the pipe structure, so
4548 * advance the pipe counter and make a new, null command. */
4549 struct pipe *pi = ctx->pipe;
4550 struct command *command = ctx->command;
4551
4552 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004553 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004554 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004555 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004556 }
4557 pi->num_cmds++;
4558 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004559 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004560 } else {
4561 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4562 }
4563
4564 /* Only real trickiness here is that the uncommitted
4565 * command structure is not counted in pi->num_cmds. */
4566 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004567 ctx->command = command = &pi->cmds[pi->num_cmds];
4568 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004569 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004570 return pi->num_cmds; /* used only for 0/nonzero check */
4571}
4572
4573static void done_pipe(struct parse_context *ctx, pipe_style type)
4574{
4575 int not_null;
4576
4577 debug_printf_parse("done_pipe entered, followup %d\n", type);
4578 /* Close previous command */
4579 not_null = done_command(ctx);
4580 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004581#if HAS_KEYWORDS
4582 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4583 ctx->ctx_inverted = 0;
4584 ctx->pipe->res_word = ctx->ctx_res_w;
4585#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004586
4587 /* Without this check, even just <enter> on command line generates
4588 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004589 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004590 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004591#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004592 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004593#endif
4594#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004595 || ctx->ctx_res_w == RES_DONE
4596 || ctx->ctx_res_w == RES_FOR
4597 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004598#endif
4599#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004600 || ctx->ctx_res_w == RES_ESAC
4601#endif
4602 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004603 struct pipe *new_p;
4604 debug_printf_parse("done_pipe: adding new pipe: "
4605 "not_null:%d ctx->ctx_res_w:%d\n",
4606 not_null, ctx->ctx_res_w);
4607 new_p = new_pipe();
4608 ctx->pipe->next = new_p;
4609 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004610 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004611 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004612 * This is used to control execution.
4613 * RES_FOR and RES_IN are NOT sticky (needed to support
4614 * cases where variable or value happens to match a keyword):
4615 */
4616#if ENABLE_HUSH_LOOPS
4617 if (ctx->ctx_res_w == RES_FOR
4618 || ctx->ctx_res_w == RES_IN)
4619 ctx->ctx_res_w = RES_NONE;
4620#endif
4621#if ENABLE_HUSH_CASE
4622 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004623 ctx->ctx_res_w = RES_CASE_BODY;
4624 if (ctx->ctx_res_w == RES_CASE)
4625 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004626#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004627 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004628 /* Create the memory for command, roughly:
4629 * ctx->pipe->cmds = new struct command;
4630 * ctx->command = &ctx->pipe->cmds[0];
4631 */
4632 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004633 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004634 }
4635 debug_printf_parse("done_pipe return\n");
4636}
4637
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004638static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004639{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004640 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004641 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004642 /* Create the memory for command, roughly:
4643 * ctx->pipe->cmds = new struct command;
4644 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004645 */
4646 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004647}
4648
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004649/* If a reserved word is found and processed, parse context is modified
4650 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004651 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004652#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004653struct reserved_combo {
4654 char literal[6];
4655 unsigned char res;
4656 unsigned char assignment_flag;
4657 int flag;
4658};
4659enum {
4660 FLAG_END = (1 << RES_NONE ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004661# if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004662 FLAG_IF = (1 << RES_IF ),
4663 FLAG_THEN = (1 << RES_THEN ),
4664 FLAG_ELIF = (1 << RES_ELIF ),
4665 FLAG_ELSE = (1 << RES_ELSE ),
4666 FLAG_FI = (1 << RES_FI ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004667# endif
4668# if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004669 FLAG_FOR = (1 << RES_FOR ),
4670 FLAG_WHILE = (1 << RES_WHILE),
4671 FLAG_UNTIL = (1 << RES_UNTIL),
4672 FLAG_DO = (1 << RES_DO ),
4673 FLAG_DONE = (1 << RES_DONE ),
4674 FLAG_IN = (1 << RES_IN ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004675# endif
4676# if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004677 FLAG_MATCH = (1 << RES_MATCH),
4678 FLAG_ESAC = (1 << RES_ESAC ),
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004679# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004680 FLAG_START = (1 << RES_XXXX ),
4681};
4682
4683static const struct reserved_combo* match_reserved_word(o_string *word)
4684{
Eric Andersen25f27032001-04-26 23:22:31 +00004685 /* Mostly a list of accepted follow-up reserved words.
4686 * FLAG_END means we are done with the sequence, and are ready
4687 * to turn the compound list into a command.
4688 * FLAG_START means the word must start a new compound list.
4689 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004690 static const struct reserved_combo reserved_list[] = {
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004691# if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004692 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4693 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4694 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4695 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4696 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4697 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004698# endif
4699# if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004700 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4701 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4702 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4703 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4704 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4705 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004706# endif
4707# if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004708 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4709 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004710# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004711 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004712 const struct reserved_combo *r;
4713
4714 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4715 if (strcmp(word->data, r->literal) == 0)
4716 return r;
4717 }
4718 return NULL;
4719}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004720/* Return 0: not a keyword, 1: keyword
4721 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004722static int reserved_word(o_string *word, struct parse_context *ctx)
4723{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004724# if ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004725 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004726 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004727 };
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004728# endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004729 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004730
Denis Vlasenkobb929512009-04-16 10:59:40 +00004731 if (word->o_quoted)
4732 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004733 r = match_reserved_word(word);
4734 if (!r)
4735 return 0;
4736
4737 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004738# if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004739 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4740 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004741 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004742 } else
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004743# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004744 if (r->flag == 0) { /* '!' */
4745 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004746 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004747 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004748 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004749 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004750 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004751 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004752 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004753 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004754
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004755 old = xmalloc(sizeof(*old));
4756 debug_printf_parse("push stack %p\n", old);
4757 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004758 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004759 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004760 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004761 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004762 ctx->ctx_res_w = RES_SNTX;
4763 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004764 } else {
4765 /* "{...} fi" is ok. "{...} if" is not
4766 * Example:
4767 * if { echo foo; } then { echo bar; } fi */
4768 if (ctx->command->group)
4769 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004770 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004771
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004772 ctx->ctx_res_w = r->res;
4773 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004774 word->o_assignment = r->assignment_flag;
4775
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004776 if (ctx->old_flag & FLAG_END) {
4777 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004778
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004779 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004780 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004781 old = ctx->stack;
4782 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004783 old->command->cmd_type = CMD_NORMAL;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004784# if !BB_MMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004785 o_addstr(&old->as_string, ctx->as_string.data);
4786 o_free_unsafe(&ctx->as_string);
4787 old->command->group_as_string = xstrdup(old->as_string.data);
4788 debug_printf_parse("pop, remembering as:'%s'\n",
4789 old->command->group_as_string);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004790# endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004791 *ctx = *old; /* physical copy */
4792 free(old);
4793 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004794 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004795}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02004796#endif /* HAS_KEYWORDS */
Eric Andersen25f27032001-04-26 23:22:31 +00004797
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004798/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004799 * Normal return is 0. Syntax errors return 1.
4800 * Note: on return, word is reset, but not o_free'd!
4801 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004802static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004803{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004804 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004805
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004806 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004807 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004808 debug_printf_parse("done_word return 0: true null, ignored\n");
4809 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004810 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004811
Eric Andersen25f27032001-04-26 23:22:31 +00004812 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004813 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4814 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004815 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4816 * "2.7 Redirection
4817 * ...the word that follows the redirection operator
4818 * shall be subjected to tilde expansion, parameter expansion,
4819 * command substitution, arithmetic expansion, and quote
4820 * removal. Pathname expansion shall not be performed
4821 * on the word by a non-interactive shell; an interactive
4822 * shell may perform it, but shall do so only when
4823 * the expansion would result in one word."
4824 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004825 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004826 /* Cater for >\file case:
4827 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4828 * Same with heredocs:
4829 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4830 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004831 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4832 unbackslash(ctx->pending_redirect->rd_filename);
4833 /* Is it <<"HEREDOC"? */
4834 if (word->o_quoted) {
4835 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4836 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004837 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004838 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004839 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004840 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004841 /* If this word wasn't an assignment, next ones definitely
4842 * can't be assignments. Even if they look like ones. */
4843 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4844 && word->o_assignment != WORD_IS_KEYWORD
4845 ) {
4846 word->o_assignment = NOT_ASSIGNMENT;
4847 } else {
4848 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4849 command->assignment_cnt++;
4850 word->o_assignment = MAYBE_ASSIGNMENT;
4851 }
4852
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004853#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004854# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004855 if (ctx->ctx_dsemicolon
4856 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4857 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004858 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004859 /* ctx->ctx_res_w = RES_MATCH; */
4860 ctx->ctx_dsemicolon = 0;
4861 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004862# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004863 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004864# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004865 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4866 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004867# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004868# if ENABLE_HUSH_CASE
4869 && ctx->ctx_res_w != RES_CASE
4870# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004871 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004872 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004873 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004874 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004875 debug_printf_parse("done_word return %d\n",
4876 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004877 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004878 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004879# ifdef CMD_SINGLEWORD_NOGLOB_COND
4880 if (strcmp(word->data, "export") == 0
4881# if ENABLE_HUSH_LOCAL
4882 || strcmp(word->data, "local") == 0
4883# endif
4884 ) {
4885 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4886 } else
4887# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004888# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004889 if (strcmp(word->data, "[[") == 0) {
4890 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4891 }
4892 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004893# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004894 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004895#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004896 if (command->group) {
4897 /* "{ echo foo; } echo bar" - bad */
4898 syntax_error_at(word->data);
4899 debug_printf_parse("done_word return 1: syntax error, "
4900 "groups and arglists don't mix\n");
4901 return 1;
4902 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004903 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004904 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4905 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004906 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004907 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004908 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004909 char *p = word->data;
4910 while (p[0] == SPECIAL_VAR_SYMBOL
4911 && (p[1] & 0x7f) == '@'
4912 && p[2] == SPECIAL_VAR_SYMBOL
4913 ) {
4914 p += 3;
4915 }
4916 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004917 /* saw no "$@", or not only "$@" but some
4918 * real text is there too */
4919 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004920 * e.g. "", $empty"" etc to not disappear */
4921 o_addchr(word, SPECIAL_VAR_SYMBOL);
4922 o_addchr(word, SPECIAL_VAR_SYMBOL);
4923 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004924 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004925 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004926 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004927 }
Eric Andersen25f27032001-04-26 23:22:31 +00004928
Denis Vlasenko06810332007-05-21 23:30:54 +00004929#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004930 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004931 if (word->o_quoted
4932 || !is_well_formed_var_name(command->argv[0], '\0')
4933 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004934 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004935 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004936 return 1;
4937 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004938 /* Force FOR to have just one word (variable name) */
4939 /* NB: basically, this makes hush see "for v in ..."
4940 * syntax as if it is "for v; in ...". FOR and IN become
4941 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004942 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004943 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004944#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004945#if ENABLE_HUSH_CASE
4946 /* Force CASE to have just one word */
4947 if (ctx->ctx_res_w == RES_CASE) {
4948 done_pipe(ctx, PIPE_SEQ);
4949 }
4950#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004951
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004952 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004953
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004954 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004955 return 0;
4956}
4957
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004958
4959/* Peek ahead in the input to find out if we have a "&n" construct,
4960 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004961 * Return:
4962 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4963 * REDIRFD_SYNTAX_ERR if syntax error,
4964 * REDIRFD_TO_FILE if no & was seen,
4965 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004966 */
4967#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004968#define parse_redir_right_fd(as_string, input) \
4969 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004970#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004971static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004972{
4973 int ch, d, ok;
4974
4975 ch = i_peek(input);
4976 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004977 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004978
4979 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004980 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004981 ch = i_peek(input);
4982 if (ch == '-') {
4983 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004984 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004985 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004986 }
4987 d = 0;
4988 ok = 0;
4989 while (ch != EOF && isdigit(ch)) {
4990 d = d*10 + (ch-'0');
4991 ok = 1;
4992 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004993 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004994 ch = i_peek(input);
4995 }
4996 if (ok) return d;
4997
4998//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4999
5000 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005001 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005002}
5003
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005004/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005005 */
5006static int parse_redirect(struct parse_context *ctx,
5007 int fd,
5008 redir_type style,
5009 struct in_str *input)
5010{
5011 struct command *command = ctx->command;
5012 struct redir_struct *redir;
5013 struct redir_struct **redirp;
5014 int dup_num;
5015
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005016 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005017 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005018 /* Check for a '>&1' type redirect */
5019 dup_num = parse_redir_right_fd(&ctx->as_string, input);
5020 if (dup_num == REDIRFD_SYNTAX_ERR)
5021 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005022 } else {
5023 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005024 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005025 if (dup_num) { /* <<-... */
5026 ch = i_getch(input);
5027 nommu_addchr(&ctx->as_string, ch);
5028 ch = i_peek(input);
5029 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005030 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005031
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005032 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005033 int ch = i_peek(input);
5034 if (ch == '|') {
5035 /* >|FILE redirect ("clobbering" >).
5036 * Since we do not support "set -o noclobber" yet,
5037 * >| and > are the same for now. Just eat |.
5038 */
5039 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005040 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005041 }
5042 }
5043
5044 /* Create a new redir_struct and append it to the linked list */
5045 redirp = &command->redirects;
5046 while ((redir = *redirp) != NULL) {
5047 redirp = &(redir->next);
5048 }
5049 *redirp = redir = xzalloc(sizeof(*redir));
5050 /* redir->next = NULL; */
5051 /* redir->rd_filename = NULL; */
5052 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005053 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005054
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005055 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5056 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005057
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005058 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005059 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005060 /* Erik had a check here that the file descriptor in question
5061 * is legit; I postpone that to "run time"
5062 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005063 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5064 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005065 } else {
5066 /* Set ctx->pending_redirect, so we know what to do at the
5067 * end of the next parsed word. */
5068 ctx->pending_redirect = redir;
5069 }
5070 return 0;
5071}
5072
Eric Andersen25f27032001-04-26 23:22:31 +00005073/* If a redirect is immediately preceded by a number, that number is
5074 * supposed to tell which file descriptor to redirect. This routine
5075 * looks for such preceding numbers. In an ideal world this routine
5076 * needs to handle all the following classes of redirects...
5077 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5078 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5079 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5080 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005081 *
5082 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5083 * "2.7 Redirection
5084 * ... If n is quoted, the number shall not be recognized as part of
5085 * the redirection expression. For example:
5086 * echo \2>a
5087 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005088 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005089 *
5090 * A -1 return means no valid number was found,
5091 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005092 */
5093static int redirect_opt_num(o_string *o)
5094{
5095 int num;
5096
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005097 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005098 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005099 num = bb_strtou(o->data, NULL, 10);
5100 if (errno || num < 0)
5101 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005102 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005103 return num;
5104}
5105
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005106#if BB_MMU
5107#define fetch_till_str(as_string, input, word, skip_tabs) \
5108 fetch_till_str(input, word, skip_tabs)
5109#endif
5110static char *fetch_till_str(o_string *as_string,
5111 struct in_str *input,
5112 const char *word,
5113 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005114{
5115 o_string heredoc = NULL_O_STRING;
5116 int past_EOL = 0;
5117 int ch;
5118
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005119 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005120 while (1) {
5121 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005122 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005123 if (ch == '\n') {
5124 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5125 heredoc.data[past_EOL] = '\0';
5126 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5127 return heredoc.data;
5128 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005129 do {
5130 o_addchr(&heredoc, ch);
5131 past_EOL = heredoc.length;
5132 jump_in:
5133 do {
5134 ch = i_getch(input);
5135 nommu_addchr(as_string, ch);
5136 } while (skip_tabs && ch == '\t');
5137 } while (ch == '\n');
5138 }
5139 if (ch == EOF) {
5140 o_free_unsafe(&heredoc);
5141 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005142 }
5143 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005144 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005145 }
5146}
5147
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005148/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5149 * and load them all. There should be exactly heredoc_cnt of them.
5150 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005151static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5152{
5153 struct pipe *pi = ctx->list_head;
5154
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005155 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005156 int i;
5157 struct command *cmd = pi->cmds;
5158
5159 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5160 pi->num_cmds,
5161 cmd->argv ? cmd->argv[0] : "NONE");
5162 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005163 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005164
5165 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5166 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005167 while (redir) {
5168 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005169 char *p;
5170
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005171 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005172 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005173 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005174 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005175 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005176 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005177 return 1;
5178 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005179 free(redir->rd_filename);
5180 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005181 heredoc_cnt--;
5182 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005183 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005184 }
5185 cmd++;
5186 }
5187 pi = pi->next;
5188 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005189#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005190 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005191 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005192 bb_error_msg_and_die("heredoc BUG 2");
5193#endif
5194 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005195}
5196
5197
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005198#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005199static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005200{
5201 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005202 int pid, channel[2];
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005203# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005204 char **to_free;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005205# endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005206
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005207 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005208 pid = BB_MMU ? fork() : vfork();
5209 if (pid < 0)
5210 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005211
Denis Vlasenko05743d72008-02-10 12:10:08 +00005212 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005213 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005214 /* Process substitution is not considered to be usual
5215 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005216 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5217 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005218 bb_signals(0
5219 + (1 << SIGTSTP)
5220 + (1 << SIGTTIN)
5221 + (1 << SIGTTOU)
5222 , SIG_IGN);
Denys Vlasenko76ace252009-10-12 15:25:01 +02005223 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005224 close(channel[0]); /* NB: close _first_, then move fd! */
5225 xmove_fd(channel[1], 1);
5226 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005227 IF_HUSH_JOB(G.run_list_level = 1;)
Denys Vlasenko91836ba2009-09-23 01:46:19 +02005228 /* Awful hack for `trap` or $(trap).
5229 *
5230 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5231 * contains an example where "trap" is executed in a subshell:
5232 *
5233 * save_traps=$(trap)
5234 * ...
5235 * eval "$save_traps"
5236 *
5237 * Standard does not say that "trap" in subshell shall print
5238 * parent shell's traps. It only says that its output
5239 * must have suitable form, but then, in the above example
5240 * (which is not supposed to be normative), it implies that.
5241 *
5242 * bash (and probably other shell) does implement it
5243 * (traps are reset to defaults, but "trap" still shows them),
5244 * but as a result, "trap" logic is hopelessly messed up:
5245 *
5246 * # trap
5247 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5248 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5249 * # true | trap <--- trap is in subshell - no output (ditto)
5250 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5251 * trap -- 'echo Ho' SIGWINCH
5252 * # echo `(trap)` <--- in subshell in subshell - output
5253 * trap -- 'echo Ho' SIGWINCH
5254 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5255 * trap -- 'echo Ho' SIGWINCH
5256 *
5257 * The rules when to forget and when to not forget traps
5258 * get really complex and nonsensical.
5259 *
5260 * Our solution: ONLY bare $(trap) or `trap` is special.
5261 */
5262 s = skip_whitespace(s);
5263 if (strncmp(s, "trap", 4) == 0 && (*skip_whitespace(s + 4) == '\0'))
5264 {
5265 static const char *const argv[] = { NULL, NULL };
5266 builtin_trap((char**)argv);
5267 exit(0); /* not _exit() - we need to fflush */
5268 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005269# if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005270 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005271 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005272 _exit(G.last_exitcode);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005273# else
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005274 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005275 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5276 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005277 * echo OK
5278 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005279 re_execute_shell(&to_free,
5280 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005281 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005282 G.global_argv + 1,
5283 NULL);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005284# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005285 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005286
5287 /* parent */
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005288# if ENABLE_HUSH_FAST
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005289 G.count_SIGCHLD++;
5290//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 +02005291# endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005292 enable_restore_tty_pgrp_on_exit();
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005293# if !BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005294 free(to_free);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005295# endif
Eric Andersen25f27032001-04-26 23:22:31 +00005296 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00005297 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00005298 return pf;
5299}
5300
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005301/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005302static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005303{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005304 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005305 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005306 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005307
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005308 pf = generate_stream_from_string(s);
5309 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00005310 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005311 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00005312
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005313 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005314 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005315 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005316 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005317 if (ch == '\n') {
5318 eol_cnt++;
5319 continue;
5320 }
5321 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005322 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005323 eol_cnt--;
5324 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005325 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005326 }
5327
5328 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005329 /* Note: we got EOF, and we just close the read end of the pipe.
5330 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005331 * Try these:
5332 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5333 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005334 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005335 fclose(pf);
5336 debug_printf("closed FILE from child. return 0\n");
5337 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005338}
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005339#endif /* ENABLE_HUSH_TICK */
Eric Andersen25f27032001-04-26 23:22:31 +00005340
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005341static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005342 struct in_str *input, int ch)
5343{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005344 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005345 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005346 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005347 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005348 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005349 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005350
5351 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005352#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005353 if (ch == '(' && !dest->o_quoted) {
5354 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005355 if (done_word(dest, ctx))
5356 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005357 if (!command->argv)
5358 goto skip; /* (... */
5359 if (command->argv[1]) { /* word word ... (... */
5360 syntax_error_unexpected_ch('(');
5361 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005362 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005363 /* it is "word(..." or "word (..." */
5364 do
5365 ch = i_getch(input);
5366 while (ch == ' ' || ch == '\t');
5367 if (ch != ')') {
5368 syntax_error_unexpected_ch(ch);
5369 return 1;
5370 }
5371 nommu_addchr(&ctx->as_string, ch);
5372 do
5373 ch = i_getch(input);
5374 while (ch == ' ' || ch == '\t' || ch == '\n');
5375 if (ch != '{') {
5376 syntax_error_unexpected_ch(ch);
5377 return 1;
5378 }
5379 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005380 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005381 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005382 }
5383#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005384 if (command->argv /* word [word]{... */
5385 || dest->length /* word{... */
5386 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005387 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005388 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005389 debug_printf_parse("parse_group return 1: "
5390 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005391 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005392 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005393
5394#if ENABLE_HUSH_FUNCTIONS
5395 skip:
5396#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005397 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005398 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005399 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005400 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005401 } else {
5402 /* bash does not allow "{echo...", requires whitespace */
5403 ch = i_getch(input);
5404 if (ch != ' ' && ch != '\t' && ch != '\n') {
5405 syntax_error_unexpected_ch(ch);
5406 return 1;
5407 }
5408 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005409 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005410
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005411 {
5412#if !BB_MMU
5413 char *as_string = NULL;
5414#endif
5415 pipe_list = parse_stream(&as_string, input, endch);
5416#if !BB_MMU
5417 if (as_string)
5418 o_addstr(&ctx->as_string, as_string);
5419#endif
5420 /* empty ()/{} or parse error? */
5421 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005422 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005423#if !BB_MMU
5424 free(as_string);
5425#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005426 debug_printf_parse("parse_group return 1: "
5427 "parse_stream returned %p\n", pipe_list);
5428 return 1;
5429 }
5430 command->group = pipe_list;
5431#if !BB_MMU
5432 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5433 command->group_as_string = as_string;
5434 debug_printf_parse("end of group, remembering as:'%s'\n",
5435 command->group_as_string);
5436#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005437 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005438 debug_printf_parse("parse_group return 0\n");
5439 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005440 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005441}
5442
Mike Frysinger98c52642009-04-02 10:02:37 +00005443#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005444/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005445static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005446/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005447static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005448{
5449 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005450 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005451 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005452 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005453 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005454 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005455 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005456 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005457 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005458 }
5459}
5460/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005461static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005462{
5463 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005464 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005465 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005466 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005467 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005468 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005469 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005470 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005471 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005472 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005473 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005474 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005475 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005476 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005477 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005478 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005479 continue;
5480 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005481 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005482 }
5483}
5484/* Process `cmd` - copy contents until "`" is seen. Complicated by
5485 * \` quoting.
5486 * "Within the backquoted style of command substitution, backslash
5487 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5488 * The search for the matching backquote shall be satisfied by the first
5489 * backquote found without a preceding backslash; during this search,
5490 * if a non-escaped backquote is encountered within a shell comment,
5491 * a here-document, an embedded command substitution of the $(command)
5492 * form, or a quoted string, undefined results occur. A single-quoted
5493 * or double-quoted string that begins, but does not end, within the
5494 * "`...`" sequence produces undefined results."
5495 * Example Output
5496 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5497 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005498static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005499{
5500 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005501 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005502 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005503 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005504 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005505 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005506 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005507 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005508 if (ch == '\\') {
5509 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005510 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005511 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005512 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005513 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005514 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005515 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005516 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005517 ch = ch2;
5518 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005519 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005520 }
5521}
5522/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5523 * quoting and nested ()s.
5524 * "With the $(command) style of command substitution, all characters
5525 * following the open parenthesis to the matching closing parenthesis
5526 * constitute the command. Any valid shell script can be used for command,
5527 * except a script consisting solely of redirections which produces
5528 * unspecified results."
5529 * Example Output
5530 * echo $(echo '(TEST)' BEST) (TEST) BEST
5531 * echo $(echo 'TEST)' BEST) TEST) BEST
5532 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5533 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005534static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005535{
5536 int count = 0;
5537 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005538 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005539 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005540 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005541 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005542 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005543 if (ch == '(')
5544 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005545 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005546 if (--count < 0) {
5547 if (!dbl)
5548 break;
5549 if (i_peek(input) == ')') {
5550 i_getch(input);
5551 break;
5552 }
5553 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005554 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005555 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005556 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005557 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005558 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005559 continue;
5560 }
5561 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005562 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005563 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005564 continue;
5565 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005566 if (ch == '\\') {
5567 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005568 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005569 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005570 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005571 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005572 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005573 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005574 continue;
5575 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005576 }
5577}
Mike Frysinger98c52642009-04-02 10:02:37 +00005578#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005579
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005580/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005581#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005582#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005583 handle_dollar(dest, input)
5584#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005585static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005586 o_string *dest,
5587 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005588{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005589 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005590 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005591
5592 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005593 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005594 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005595 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005596 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005597 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005598 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005599 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005600 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005601 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005602 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005603 if (!isalnum(ch) && ch != '_')
5604 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005605 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005606 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005607 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005608 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005609 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005610 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005611 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005612 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005613 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005614 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005615 o_addchr(dest, ch | quote_mask);
5616 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005617 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005618 case '$': /* pid */
5619 case '!': /* last bg pid */
5620 case '?': /* last exit code */
5621 case '#': /* number of args */
5622 case '*': /* args */
5623 case '@': /* args */
5624 goto make_one_char_var;
5625 case '{': {
5626 bool first_char, all_digits;
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005627 int expansion;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005628
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005629 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005630 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005631 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5632
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005633 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005634 expansion = 0;
5635 first_char = true;
5636 all_digits = false;
5637 while (1) {
5638 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005639 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005640 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005641 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005642 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005643
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005644 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005645 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005646 /* ${#var}: length of var contents */
5647 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005648 }
5649 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005650 all_digits = true;
5651 goto char_ok;
5652 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005653 /* They're being verbose and doing ${?} */
5654 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5655 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005656 }
5657
5658 if (expansion < 2
5659 && ( (all_digits && !isdigit(ch))
5660 || (!all_digits && !isalnum(ch) && ch != '_')
5661 )
5662 ) {
5663 /* handle parameter expansions
5664 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5665 */
5666 if (first_char)
5667 goto case_default;
5668 switch (ch) {
5669 case ':': /* null modifier */
5670 if (expansion == 0) {
5671 debug_printf_parse(": null modifier\n");
5672 ++expansion;
5673 break;
5674 }
5675 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005676 case '#': /* remove prefix */
5677 case '%': /* remove suffix */
5678 if (expansion == 0) {
5679 debug_printf_parse(": remove suffix/prefix\n");
5680 expansion = 2;
5681 break;
5682 }
5683 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005684 case '-': /* default value */
5685 case '=': /* assign default */
5686 case '+': /* alternative */
5687 case '?': /* error indicate */
5688 debug_printf_parse(": parameter expansion\n");
5689 expansion = 2;
5690 break;
5691 default:
5692 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005693 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005694 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5695 return 1;
5696 }
5697 }
5698 char_ok:
5699 debug_printf_parse(": '%c'\n", ch);
5700 o_addchr(dest, ch | quote_mask);
5701 quote_mask = 0;
5702 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005703 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005704 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5705 break;
5706 }
Denys Vlasenkoc0836532009-10-19 13:13:06 +02005707#if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005708 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005709# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005710 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005711# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005712 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005713 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005714# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005715 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005716 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005717 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005718 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5719 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005720# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005721 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005722# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005723 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005724# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005725 if (as_string) {
5726 o_addstr(as_string, dest->data + pos);
5727 o_addchr(as_string, ')');
5728 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005729 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005730# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005731 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005732 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005733 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005734# endif
5735# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005736 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5737 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005738# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005739 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005740# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005741 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005742# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005743 if (as_string) {
5744 o_addstr(as_string, dest->data + pos);
5745 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005746 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005747# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005748 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005749# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005750 break;
5751 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005752#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005753 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005754 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005755 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005756 ch = i_peek(input);
5757 if (isalnum(ch)) { /* it's $_name or $_123 */
5758 ch = '_';
5759 goto make_var;
5760 }
5761 /* else: it's $_ */
Denys Vlasenko69b1cef2009-09-21 10:21:44 +02005762 /* TODO: $_ and $-: */
5763 /* $_ Shell or shell script name; or last argument of last command
5764 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
5765 * but in command's env, set to full pathname used to invoke it */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005766 /* $- Option flags set by set builtin or shell options (-i etc) */
5767 default:
5768 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005769 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005770 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005771 return 0;
5772}
5773
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005774#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005775#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005776 parse_stream_dquoted(dest, input, dquote_end)
5777#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005778static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005779 o_string *dest,
5780 struct in_str *input,
5781 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005782{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005783 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005784 int next;
5785
5786 again:
5787 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005788 if (ch != EOF)
5789 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005790 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005791 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005792 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005793 debug_printf_parse("parse_stream_dquoted return 0\n");
5794 return 0;
5795 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005796 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005797 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005798 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005799 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005800 }
5801 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005802 if (ch != '\n') {
5803 next = i_peek(input);
5804 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005805 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005806 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005807 if (ch == '\\') {
5808 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005809 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005810 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005811 }
5812 /* bash:
5813 * "The backslash retains its special meaning [in "..."]
5814 * only when followed by one of the following characters:
5815 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005816 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005817 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005818 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005819 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005820 if (ch != '\n') {
5821 o_addqchr(dest, ch);
5822 nommu_addchr(as_string, ch);
5823 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005824 } else {
5825 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005826 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005827 }
5828 goto again;
5829 }
5830 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005831 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005832 debug_printf_parse("parse_stream_dquoted return 1: "
5833 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005834 return 1;
5835 }
5836 goto again;
5837 }
5838#if ENABLE_HUSH_TICK
5839 if (ch == '`') {
5840 //int pos = dest->length;
5841 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5842 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005843 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005844 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5845 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005846 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005847 }
5848#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005849 o_addQchr(dest, ch);
5850 if (ch == '='
5851 && (dest->o_assignment == MAYBE_ASSIGNMENT
5852 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005853 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005854 ) {
5855 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5856 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005857 goto again;
5858}
5859
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005860/*
5861 * Scan input until EOF or end_trigger char.
5862 * Return a list of pipes to execute, or NULL on EOF
5863 * or if end_trigger character is met.
5864 * On syntax error, exit is shell is not interactive,
5865 * reset parsing machinery and start parsing anew,
5866 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005867 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005868static struct pipe *parse_stream(char **pstring,
5869 struct in_str *input,
5870 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005871{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005872 struct parse_context ctx;
5873 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005874 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005875 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005876
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005877 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005878 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005879 * found. When recursing, quote state is passed in via dest->o_escape.
5880 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005881 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005882 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005883 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005884
Denys Vlasenkof37eb392009-10-18 11:46:35 +02005885 /* If very first arg is "" or '', dest.data may end up NULL.
5886 * Preventing this: */
5887 o_addchr(&dest, '\0');
5888 dest.length = 0;
5889
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005890 G.ifs = get_local_var_value("IFS");
5891 if (G.ifs == NULL)
5892 G.ifs = " \t\n";
5893
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005894 reset:
5895#if ENABLE_HUSH_INTERACTIVE
5896 input->promptmode = 0; /* PS1 */
5897#endif
5898 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5899 initialize_context(&ctx);
5900 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005901 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005902 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005903 const char *is_ifs;
5904 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005905 int ch;
5906 int next;
5907 int redir_fd;
5908 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005909
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005910 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005911 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005912 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005913 goto parse_error;
5914 }
5915 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005916 is_in_dquote = 0;
5917 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005918 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005919 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5920 ch, ch, dest.o_escape);
5921 if (ch == EOF) {
5922 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005923
5924 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005925 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005926 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005927 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005928 /* end_trigger == '}' case errors out earlier,
5929 * checking only ')' */
5930 if (end_trigger == ')') {
5931 syntax_error_unterm_ch('('); /* exits */
5932 /* goto parse_error; */
5933 }
5934
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005935 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005936 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005937 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005938 o_free(&dest);
5939 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005940 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005941 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005942 /* (this makes bare "&" cmd a no-op.
5943 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005944 if (pi->num_cmds == 0
5945 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5946 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005947 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005948 pi = NULL;
5949 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005950#if !BB_MMU
5951 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5952 if (pstring)
5953 *pstring = ctx.as_string.data;
5954 else
5955 o_free_unsafe(&ctx.as_string);
5956#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005957 debug_leave();
5958 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005959 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005960 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005961 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005962 is_ifs = strchr(G.ifs, ch);
5963 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005964 "\\$\"" IF_HUSH_TICK("`") /* always special */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005965 , ch);
5966
5967 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005968 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005969 o_addQchr(&dest, ch);
5970 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5971 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005972 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005973 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005974 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005975 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005976 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005977 continue;
5978 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005979
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005980 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005981 if (done_word(&dest, &ctx)) {
5982 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005983 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005984 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005985#if ENABLE_HUSH_CASE
5986 /* "case ... in <newline> word) ..." -
5987 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005988 if (ctx.command->argv == NULL
5989 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005990 ) {
5991 continue;
5992 }
5993#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005994 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005995 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005996 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5997 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005998 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005999 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00006000 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006001 heredoc_cnt = 0;
6002 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006003 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006004 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00006005 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006006 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006007 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006008 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006009
6010 /* "cmd}" or "cmd }..." without semicolon or &:
6011 * } is an ordinary char in this case, even inside { cmd; }
6012 * Pathological example: { ""}; } should exec "}" cmd
6013 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006014 if (ch == '}') {
6015 if (!IS_NULL_CMD(ctx.command) /* cmd } */
6016 || dest.length != 0 /* word} */
6017 || dest.o_quoted /* ""} */
6018 ) {
6019 goto ordinary_char;
6020 }
6021 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
6022 goto skip_end_trigger;
6023 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00006024 }
6025
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006026 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006027 && (ch != ';' || heredoc_cnt == 0)
6028#if ENABLE_HUSH_CASE
6029 && (ch != ')'
6030 || ctx.ctx_res_w != RES_MATCH
6031 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
6032 )
6033#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006034 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006035 if (heredoc_cnt) {
6036 /* This is technically valid:
6037 * { cat <<HERE; }; echo Ok
6038 * heredoc
6039 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006040 * HERE
6041 * but we don't support this.
6042 * We require heredoc to be in enclosing {}/(),
6043 * if any.
6044 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006045 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00006046 goto parse_error;
6047 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006048 if (done_word(&dest, &ctx)) {
6049 goto parse_error;
6050 }
6051 done_pipe(&ctx, PIPE_SEQ);
6052 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00006053 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00006054 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006055 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00006056 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006057 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006058#if !BB_MMU
6059 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
6060 if (pstring)
6061 *pstring = ctx.as_string.data;
6062 else
6063 o_free_unsafe(&ctx.as_string);
6064#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006065 debug_leave();
6066 debug_printf_parse("parse_stream return %p: "
6067 "end_trigger char found\n",
6068 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006069 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006070 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006071 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006072 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00006073 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006074 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00006075
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006076 next = '\0';
6077 if (ch != '\n') {
6078 next = i_peek(input);
6079 }
6080
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00006081 /* Catch <, > before deciding whether this word is
6082 * an assignment. a=1 2>z b=2: b=2 is still assignment */
6083 switch (ch) {
6084 case '>':
6085 redir_fd = redirect_opt_num(&dest);
6086 if (done_word(&dest, &ctx)) {
6087 goto parse_error;
6088 }
6089 redir_style = REDIRECT_OVERWRITE;
6090 if (next == '>') {
6091 redir_style = REDIRECT_APPEND;
6092 ch = i_getch(input);
6093 nommu_addchr(&ctx.as_string, ch);
6094 }
6095#if 0
6096 else if (next == '(') {
6097 syntax_error(">(process) not supported");
6098 goto parse_error;
6099 }
6100#endif
6101 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6102 goto parse_error;
6103 continue; /* back to top of while (1) */
6104 case '<':
6105 redir_fd = redirect_opt_num(&dest);
6106 if (done_word(&dest, &ctx)) {
6107 goto parse_error;
6108 }
6109 redir_style = REDIRECT_INPUT;
6110 if (next == '<') {
6111 redir_style = REDIRECT_HEREDOC;
6112 heredoc_cnt++;
6113 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6114 ch = i_getch(input);
6115 nommu_addchr(&ctx.as_string, ch);
6116 } else if (next == '>') {
6117 redir_style = REDIRECT_IO;
6118 ch = i_getch(input);
6119 nommu_addchr(&ctx.as_string, ch);
6120 }
6121#if 0
6122 else if (next == '(') {
6123 syntax_error("<(process) not supported");
6124 goto parse_error;
6125 }
6126#endif
6127 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6128 goto parse_error;
6129 continue; /* back to top of while (1) */
6130 }
6131
6132 if (dest.o_assignment == MAYBE_ASSIGNMENT
6133 /* check that we are not in word in "a=1 2>word b=1": */
6134 && !ctx.pending_redirect
6135 ) {
6136 /* ch is a special char and thus this word
6137 * cannot be an assignment */
6138 dest.o_assignment = NOT_ASSIGNMENT;
6139 }
6140
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006141 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6142
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006143 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006144 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006145 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006146 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006147 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006148 if (ch == EOF || ch == '\n')
6149 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006150 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006151 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006152 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006153 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006154 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006155 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006156 }
6157 break;
6158 case '\\':
6159 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006160 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006161 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006162 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006163 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006164 if (ch != '\n') {
6165 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006166 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006167 o_addchr(&dest, ch);
6168 nommu_addchr(&ctx.as_string, ch);
6169 /* Example: echo Hello \2>file
6170 * we need to know that word 2 is quoted */
6171 dest.o_quoted = 1;
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006172 }
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006173#if !BB_MMU
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006174 else {
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006175 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6176 ctx.as_string.data[--ctx.as_string.length] = '\0';
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006177 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006178#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006179 break;
6180 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006181 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006182 debug_printf_parse("parse_stream parse error: "
6183 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006184 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006185 }
Eric Andersen25f27032001-04-26 23:22:31 +00006186 break;
6187 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006188 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006189 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006190 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006191 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006192 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006193 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006194 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006195 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006196 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006197 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006198 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006199 }
Eric Andersen25f27032001-04-26 23:22:31 +00006200 break;
6201 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006202 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006203 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006204 if (dest.o_assignment == NOT_ASSIGNMENT)
6205 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006206 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006207#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006208 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006209#if !BB_MMU
6210 int pos;
6211#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006212 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6213 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006214#if !BB_MMU
6215 pos = dest.length;
6216#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006217 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006218#if !BB_MMU
6219 o_addstr(&ctx.as_string, dest.data + pos);
6220 o_addchr(&ctx.as_string, '`');
6221#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006222 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6223 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006224 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006225 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006226#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006227 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006228#if ENABLE_HUSH_CASE
6229 case_semi:
6230#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006231 if (done_word(&dest, &ctx)) {
6232 goto parse_error;
6233 }
6234 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006235#if ENABLE_HUSH_CASE
6236 /* Eat multiple semicolons, detect
6237 * whether it means something special */
6238 while (1) {
6239 ch = i_peek(input);
6240 if (ch != ';')
6241 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006242 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006243 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006244 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006245 ctx.ctx_dsemicolon = 1;
6246 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006247 break;
6248 }
6249 }
6250#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006251 new_cmd:
6252 /* We just finished a cmd. New one may start
6253 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006254 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006255 break;
6256 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006257 if (done_word(&dest, &ctx)) {
6258 goto parse_error;
6259 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006260 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006261 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006262 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006263 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006264 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006265 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006266 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006267 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006268 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006269 if (done_word(&dest, &ctx)) {
6270 goto parse_error;
6271 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006272#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006273 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006274 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006275#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006276 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006277 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006278 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006279 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006280 } else {
6281 /* we could pick up a file descriptor choice here
6282 * with redirect_opt_num(), but bash doesn't do it.
6283 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006284 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00006285 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006286 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006287 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006288#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006289 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006290 if (ctx.ctx_res_w == RES_MATCH
6291 && ctx.command->argv == NULL /* not (word|(... */
6292 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006293 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006294 ) {
6295 continue;
6296 }
6297#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006298 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006299 if (parse_group(&dest, &ctx, input, ch) != 0) {
6300 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006301 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006302 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006303 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006304#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006305 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006306 goto case_semi;
6307#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006308 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006309 /* proper use of this character is caught by end_trigger:
6310 * if we see {, we call parse_group(..., end_trigger='}')
6311 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006312 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006313 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006314 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006315 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006316 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006317 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006318 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006319
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006320 parse_error:
6321 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006322 struct parse_context *pctx;
6323 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006324
6325 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006326 * Sample for finding leaks on syntax error recovery path.
6327 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006328 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006329 * Samples to catch leaks at execution:
6330 * while if (true | {true;}); then echo ok; fi; do break; done
6331 * 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 +00006332 */
6333 pctx = &ctx;
6334 do {
6335 /* Update pipe/command counts,
6336 * otherwise freeing may miss some */
6337 done_pipe(pctx, PIPE_SEQ);
6338 debug_printf_clean("freeing list %p from ctx %p\n",
6339 pctx->list_head, pctx);
6340 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006341 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006342 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006343#if !BB_MMU
6344 o_free_unsafe(&pctx->as_string);
6345#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006346 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006347 if (pctx != &ctx) {
6348 free(pctx);
6349 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006350 IF_HAS_KEYWORDS(pctx = p2;)
6351 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006352 /* Free text, clear all dest fields */
6353 o_free(&dest);
6354 /* If we are not in top-level parse, we return,
6355 * our caller will propagate error.
6356 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006357 if (end_trigger != ';') {
6358#if !BB_MMU
6359 if (pstring)
6360 *pstring = NULL;
6361#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006362 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006363 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006364 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006365 /* Discard cached input, force prompt */
6366 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006367 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006368 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006369 }
Eric Andersen25f27032001-04-26 23:22:31 +00006370}
6371
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006372/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006373 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6374 * end_trigger controls how often we stop parsing
6375 * NUL: parse all, execute, return
6376 * ';': parse till ';' or newline, execute, repeat till EOF
6377 */
6378static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006379{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006380 while (1) {
6381 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006382
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006383 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006384 if (!pipe_list) /* EOF */
6385 break;
6386 debug_print_tree(pipe_list, 0);
6387 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6388 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006389 }
Eric Andersen25f27032001-04-26 23:22:31 +00006390}
6391
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006392static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006393{
6394 struct in_str input;
6395 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006396 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006397}
6398
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006399static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006400{
Eric Andersen25f27032001-04-26 23:22:31 +00006401 struct in_str input;
6402 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006403 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006404}
6405
Denis Vlasenkof9375282009-04-05 19:13:39 +00006406/* Called a few times only (or even once if "sh -c") */
6407static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006408{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006409 unsigned sig;
6410 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006411
Denis Vlasenkof9375282009-04-05 19:13:39 +00006412 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006413 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006414 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006415 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006416 mask |= SPECIAL_JOB_SIGS;
6417 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006418 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006419
Denis Vlasenkof9375282009-04-05 19:13:39 +00006420 if (!second_time)
6421 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6422 sig = 0;
6423 while (mask) {
6424 if (mask & 1)
6425 sigaddset(&G.blocked_set, sig);
6426 mask >>= 1;
6427 sig++;
6428 }
6429 sigdelset(&G.blocked_set, SIGCHLD);
6430
6431 sigprocmask(SIG_SETMASK, &G.blocked_set,
6432 second_time ? NULL : &G.inherited_set);
6433 /* POSIX allows shell to re-enable SIGCHLD
6434 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006435#if ENABLE_HUSH_FAST
6436 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006437 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006438 signal(SIGCHLD, SIGCHLD_handler);
6439#else
6440 if (!second_time)
6441 signal(SIGCHLD, SIG_DFL);
6442#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006443}
6444
6445#if ENABLE_HUSH_JOB
6446/* helper */
6447static void maybe_set_to_sigexit(int sig)
6448{
6449 void (*handler)(int);
6450 /* non_DFL_mask'ed signals are, well, masked,
6451 * no need to set handler for them.
6452 */
6453 if (!((G.non_DFL_mask >> sig) & 1)) {
6454 handler = signal(sig, sigexit);
6455 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6456 signal(sig, handler);
6457 }
6458}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006459/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006460static void set_fatal_handlers(void)
6461{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006462 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006463 if (HUSH_DEBUG) {
6464 maybe_set_to_sigexit(SIGILL );
6465 maybe_set_to_sigexit(SIGFPE );
6466 maybe_set_to_sigexit(SIGBUS );
6467 maybe_set_to_sigexit(SIGSEGV);
6468 maybe_set_to_sigexit(SIGTRAP);
6469 } /* else: hush is perfect. what SEGV? */
6470 maybe_set_to_sigexit(SIGABRT);
6471 /* bash 3.2 seems to handle these just like 'fatal' ones */
6472 maybe_set_to_sigexit(SIGPIPE);
6473 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006474 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006475 * if we aren't interactive... but in this case
6476 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006477 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006478 /*maybe_set_to_sigexit(SIGTERM);*/
6479 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006480}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006481#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006482
Denis Vlasenkod5762932009-03-31 11:22:57 +00006483static int set_mode(const char cstate, const char mode)
6484{
6485 int state = (cstate == '-' ? 1 : 0);
6486 switch (mode) {
6487 case 'n': G.fake_mode = state; break;
6488 case 'x': /*G.debug_mode = state;*/ break;
6489 default: return EXIT_FAILURE;
6490 }
6491 return EXIT_SUCCESS;
6492}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006493
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006494int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006495int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006496{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006497 static const struct variable const_shell_ver = {
6498 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006499 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006500 .max_len = 1, /* 0 can provoke free(name) */
6501 .flg_export = 1,
6502 .flg_read_only = 1,
6503 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006504 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006505 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006506 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006507 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006508 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006509
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006510 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006511 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006512 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006513#if !BB_MMU
6514 G.argv0_for_re_execing = argv[0];
6515#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006516 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006517 G.shell_ver = const_shell_ver; /* copying struct here */
6518 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006519 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006520 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6521 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006522 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006523 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006524 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006525 if (e) while (*e) {
6526 char *value = strchr(*e, '=');
6527 if (value) { /* paranoia */
6528 cur_var->next = xzalloc(sizeof(*cur_var));
6529 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006530 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006531 cur_var->max_len = strlen(*e);
6532 cur_var->flg_export = 1;
6533 }
6534 e++;
6535 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006536 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006537 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006538 putenv((char *)hush_version_str);
6539
6540 /* Export PWD */
6541 set_pwd_var(/*exp:*/ 1);
6542 /* bash also exports SHLVL and _,
6543 * and sets (but doesn't export) the following variables:
6544 * BASH=/bin/bash
6545 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6546 * BASH_VERSION='3.2.0(1)-release'
6547 * HOSTTYPE=i386
6548 * MACHTYPE=i386-pc-linux-gnu
6549 * OSTYPE=linux-gnu
6550 * HOSTNAME=<xxxxxxxxxx>
Denys Vlasenkodea47882009-10-09 15:40:49 +02006551 * PPID=<NNNNN> - we also do it elsewhere
Denys Vlasenko6db47842009-09-05 20:15:17 +02006552 * EUID=<NNNNN>
6553 * UID=<NNNNN>
6554 * GROUPS=()
6555 * LINES=<NNN>
6556 * COLUMNS=<NNN>
6557 * BASH_ARGC=()
6558 * BASH_ARGV=()
6559 * BASH_LINENO=()
6560 * BASH_SOURCE=()
6561 * DIRSTACK=()
6562 * PIPESTATUS=([0]="0")
6563 * HISTFILE=/<xxx>/.bash_history
6564 * HISTFILESIZE=500
6565 * HISTSIZE=500
6566 * MAILCHECK=60
6567 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6568 * SHELL=/bin/bash
6569 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6570 * TERM=dumb
6571 * OPTERR=1
6572 * OPTIND=1
6573 * IFS=$' \t\n'
6574 * PS1='\s-\v\$ '
6575 * PS2='> '
6576 * PS4='+ '
6577 */
6578
Denis Vlasenko38f63192007-01-22 09:03:07 +00006579#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006580 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006581#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006582 G.global_argc = argc;
6583 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006584 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006585 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006586
Denis Vlasenkoed782372009-04-10 00:45:02 +00006587 if (setjmp(die_jmp)) {
6588 /* xfunc has failed! die die die */
6589 /* no EXIT traps, this is an escape hatch! */
6590 G.exiting = 1;
6591 hush_exit(xfunc_error_retval);
6592 }
6593
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006594 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006595 * block_signals(0) if we are going to execute "sh <script>",
6596 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006597 * If we later decide that we are interactive, we run block_signals(0)
6598 * (or re-run block_signals(1) if we ran block_signals(0) before)
6599 * in order to intercept (more) signals.
6600 */
6601
6602 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006603 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006604 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006605 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006606 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006607#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006608 "<:$:R:V:"
6609# if ENABLE_HUSH_FUNCTIONS
6610 "F:"
6611# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006612#endif
6613 );
6614 if (opt <= 0)
6615 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006616 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006617 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006618 /* Possibilities:
6619 * sh ... -c 'script'
6620 * sh ... -c 'script' ARG0 [ARG1...]
6621 * On NOMMU, if builtin_argc != 0,
6622 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6623 * "" needs to be replaced with NULL
6624 * and BARGV vector fed to builtin function.
6625 * Note: this form never happens:
6626 * sh ... -c 'builtin' [BARGV...] ""
6627 */
Denys Vlasenkodea47882009-10-09 15:40:49 +02006628 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006629 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006630 G.root_ppid = getppid();
6631 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006632 G.global_argv = argv + optind;
6633 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006634 if (builtin_argc) {
6635 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6636 const struct built_in_command *x;
6637
6638 block_signals(0); /* 0: called 1st time */
6639 x = find_builtin(optarg);
6640 if (x) { /* paranoia */
6641 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6642 G.global_argv += builtin_argc;
6643 G.global_argv[-1] = NULL; /* replace "" */
6644 G.last_exitcode = x->function(argv + optind - 1);
6645 }
6646 goto final_return;
6647 }
6648 if (!G.global_argv[0]) {
6649 /* -c 'script' (no params): prevent empty $0 */
6650 G.global_argv--; /* points to argv[i] of 'script' */
6651 G.global_argv[0] = argv[0];
6652 G.global_argc--;
6653 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006654 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006655 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006656 goto final_return;
6657 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006658 /* Well, we cannot just declare interactiveness,
6659 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006660 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006661 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006662 case 's':
6663 /* "-s" means "read from stdin", but this is how we always
6664 * operate, so simply do nothing here. */
6665 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006666#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006667 case '<': /* "big heredoc" support */
6668 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6669 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006670 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006671 G.root_pid = bb_strtou(optarg, &optarg, 16);
6672 optarg++;
Denys Vlasenkodea47882009-10-09 15:40:49 +02006673 G.root_ppid = bb_strtou(optarg, &optarg, 16);
6674 optarg++;
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006675 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6676 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006677 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006678 optarg++;
6679 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006680# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006681 optarg++;
6682 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006683# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006684 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006685 case 'R':
6686 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02006687 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006688 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006689# if ENABLE_HUSH_FUNCTIONS
6690 case 'F': {
6691 struct function *funcp = new_function(optarg);
6692 /* funcp->name is already set to optarg */
6693 /* funcp->body is set to NULL. It's a special case. */
6694 funcp->body_as_string = argv[optind];
6695 optind++;
6696 break;
6697 }
6698# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006699#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006700 case 'n':
6701 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006702 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006703 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006704 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006705#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006706 fprintf(stderr, "Usage: sh [FILE]...\n"
6707 " or: sh -c command [args]...\n\n");
6708 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006709#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006710 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006711#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006712 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006713 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006714
Denys Vlasenkodea47882009-10-09 15:40:49 +02006715 if (!G.root_pid) {
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006716 G.root_pid = getpid();
Denys Vlasenkodea47882009-10-09 15:40:49 +02006717 G.root_ppid = getppid();
6718 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006719
6720 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006721 if (argv[0] && argv[0][0] == '-') {
6722 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006723 debug_printf("sourcing /etc/profile\n");
6724 input = fopen_for_read("/etc/profile");
6725 if (input != NULL) {
6726 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006727 block_signals(0); /* 0: called 1st time */
6728 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006729 parse_and_run_file(input);
6730 fclose(input);
6731 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006732 /* bash: after sourcing /etc/profile,
6733 * tries to source (in the given order):
6734 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006735 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006736 * bash also sources ~/.bash_logout on exit.
6737 * If called as sh, skips .bash_XXX files.
6738 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006739 }
6740
Denis Vlasenkof9375282009-04-05 19:13:39 +00006741 if (argv[optind]) {
6742 FILE *input;
6743 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006744 * "bash <script>" (which is never interactive (unless -i?))
6745 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006746 * If called as sh, does the same but with $ENV.
6747 */
6748 debug_printf("running script '%s'\n", argv[optind]);
6749 G.global_argv = argv + optind;
6750 G.global_argc = argc - optind;
6751 input = xfopen_for_read(argv[optind]);
6752 close_on_exec_on(fileno(input));
6753 if (!signal_mask_is_inited)
6754 block_signals(0); /* 0: called 1st time */
6755 parse_and_run_file(input);
6756#if ENABLE_FEATURE_CLEAN_UP
6757 fclose(input);
6758#endif
6759 goto final_return;
6760 }
6761
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006762 /* Up to here, shell was non-interactive. Now it may become one.
6763 * NB: don't forget to (re)run block_signals(0/1) as needed.
6764 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006765
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006766 /* A shell is interactive if the '-i' flag was given,
6767 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006768 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006769 * no arguments remaining or the -s flag given
6770 * standard input is a terminal
6771 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006772 * Refer to Posix.2, the description of the 'sh' utility.
6773 */
6774#if ENABLE_HUSH_JOB
6775 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04006776 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6777 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6778 if (G_saved_tty_pgrp < 0)
6779 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006780
6781 /* try to dup stdin to high fd#, >= 255 */
6782 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6783 if (G_interactive_fd < 0) {
6784 /* try to dup to any fd */
6785 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006786 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006787 /* give up */
6788 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04006789 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006790 }
6791 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006792// TODO: track & disallow any attempts of user
6793// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006794 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006795 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006796 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006797 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006798
Mike Frysinger38478a62009-05-20 04:48:06 -04006799 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006800 /* If we were run as 'hush &', sleep until we are
6801 * in the foreground (tty pgrp == our pgrp).
6802 * If we get started under a job aware app (like bash),
6803 * make sure we are now in charge so we don't fight over
6804 * who gets the foreground */
6805 while (1) {
6806 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04006807 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6808 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006809 break;
6810 /* send TTIN to ourself (should stop us) */
6811 kill(- shell_pgrp, SIGTTIN);
6812 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006813 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006814
Denis Vlasenkof9375282009-04-05 19:13:39 +00006815 /* Block some signals */
6816 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006817
Mike Frysinger38478a62009-05-20 04:48:06 -04006818 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006819 /* Set other signals to restore saved_tty_pgrp */
6820 set_fatal_handlers();
6821 /* Put ourselves in our own process group
6822 * (bash, too, does this only if ctty is available) */
6823 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6824 /* Grab control of the terminal */
6825 tcsetpgrp(G_interactive_fd, getpid());
6826 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006827 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006828 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006829 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006830 } else if (!signal_mask_is_inited) {
6831 block_signals(0); /* 0: called 1st time */
6832 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006833#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006834 /* No job control compiled in, only prompt/line editing */
6835 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006836 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6837 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006838 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006839 G_interactive_fd = dup(STDIN_FILENO);
6840 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006841 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006842 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006843 }
6844 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006845 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006846 close_on_exec_on(G_interactive_fd);
6847 block_signals(signal_mask_is_inited);
6848 } else if (!signal_mask_is_inited) {
6849 block_signals(0);
6850 }
6851#else
6852 /* We have interactiveness code disabled */
6853 if (!signal_mask_is_inited) {
6854 block_signals(0);
6855 }
6856#endif
6857 /* bash:
6858 * if interactive but not a login shell, sources ~/.bashrc
6859 * (--norc turns this off, --rcfile <file> overrides)
6860 */
6861
6862 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02006863 /* note: ash and hush share this string */
6864 printf("\n\n%s %s\n"
6865 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
6866 "\n",
6867 bb_banner,
6868 "hush - the humble shell"
6869 );
Mike Frysingerb2705e12009-03-23 08:44:02 +00006870 }
6871
Denis Vlasenkof9375282009-04-05 19:13:39 +00006872 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006873
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006874 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006875#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006876 if (G.cwd != bb_msg_unknown)
6877 free((char*)G.cwd);
6878 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006879 while (cur_var) {
6880 struct variable *tmp = cur_var;
6881 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006882 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006883 cur_var = cur_var->next;
6884 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006885 }
Eric Andersen25f27032001-04-26 23:22:31 +00006886#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006887 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006888}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006889
6890
6891#if ENABLE_LASH
6892int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6893int lash_main(int argc, char **argv)
6894{
Denys Vlasenko07934912009-08-20 03:40:04 +02006895 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006896 return hush_main(argc, argv);
6897}
6898#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006899
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02006900#if ENABLE_MSH
6901int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6902int msh_main(int argc, char **argv)
6903{
6904 //bb_error_msg("msh is deprecated, please use hush instead");
6905 return hush_main(argc, argv);
6906}
6907#endif
6908
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006909
6910/*
6911 * Built-ins
6912 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006913static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006914{
6915 return 0;
6916}
6917
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006918static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006919{
6920 int argc = 0;
6921 while (*argv) {
6922 argc++;
6923 argv++;
6924 }
Denys Vlasenko8bc7f2c2009-10-19 13:20:52 +02006925 return applet_main_func(argc, argv - argc);
Mike Frysingerccb19592009-10-15 03:31:15 -04006926}
6927
6928static int FAST_FUNC builtin_test(char **argv)
6929{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006930 return run_applet_main(argv, test_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006931}
6932
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006933static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006934{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006935 return run_applet_main(argv, echo_main);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006936}
6937
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04006938#if ENABLE_PRINTF
6939static int FAST_FUNC builtin_printf(char **argv)
6940{
Denys Vlasenkoc0836532009-10-19 13:13:06 +02006941 return run_applet_main(argv, printf_main);
Mike Frysinger4ebc76c2009-10-15 03:32:39 -04006942}
6943#endif
6944
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006945static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006946{
6947 int rcode = EXIT_SUCCESS;
6948
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006949 if (*++argv) {
6950 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006951 /* bash:
6952 * eval "echo Hi; done" ("done" is syntax error):
6953 * "echo Hi" will not execute too.
6954 */
6955 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006956 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006957 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006958 }
6959 return rcode;
6960}
6961
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006962static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006963{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006964 const char *newdir = argv[1];
6965 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006966 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006967 * bash says "bash: cd: HOME not set" and does nothing
6968 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006969 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02006970 const char *home = get_local_var_value("HOME");
6971 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006972 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006973 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006974 /* Mimic bash message exactly */
6975 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006976 return EXIT_FAILURE;
6977 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006978 /* Read current dir (get_cwd(1) is inside) and set PWD.
6979 * Note: do not enforce exporting. If PWD was unset or unexported,
6980 * set it again, but do not export. bash does the same.
6981 */
6982 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006983 return EXIT_SUCCESS;
6984}
6985
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006986static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006987{
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006988 static const char pseudo_null_str[] = { SPECIAL_VAR_SYMBOL, SPECIAL_VAR_SYMBOL, '\0' };
Denys Vlasenko3b3ccdc2009-10-19 13:24:07 +02006989 char **pp;
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006990#if !BB_MMU
6991 nommu_save_t dummy;
6992#endif
6993
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006994 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006995 return EXIT_SUCCESS; /* bash does this */
Denys Vlasenkof37eb392009-10-18 11:46:35 +02006996
6997 /* Make sure empty arguments aren't ignored */
6998 /* Example: exec ls '' */
6999 pp = argv;
7000 while (*pp) {
7001 if ((*pp)[0] == '\0')
7002 *pp = (char*)pseudo_null_str;
7003 pp++;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007004 }
Denys Vlasenkof37eb392009-10-18 11:46:35 +02007005
7006 /* Careful: we can end up here after [v]fork. Do not restore
7007 * tty pgrp then, only top-level shell process does that */
7008 if (G_saved_tty_pgrp && getpid() == G.root_pid)
7009 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
7010
7011 /* TODO: if exec fails, bash does NOT exit! We do... */
7012 pseudo_exec_argv(&dummy, argv, 0, NULL);
7013 /* never returns */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007014}
7015
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007016static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007017{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00007018 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00007019
7020 /* interactive bash:
7021 * # trap "echo EEE" EXIT
7022 * # exit
7023 * exit
7024 * There are stopped jobs.
7025 * (if there are _stopped_ jobs, running ones don't count)
7026 * # exit
7027 * exit
7028 # EEE (then bash exits)
7029 *
7030 * we can use G.exiting = -1 as indicator "last cmd was exit"
7031 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00007032
7033 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007034 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007035 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007036 /* mimic bash: exit 123abc == exit 255 + error msg */
7037 xfunc_error_retval = 255;
7038 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00007039 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007040}
7041
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007042static void print_escaped(const char *s)
7043{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007044 if (*s == '\'')
7045 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007046 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007047 const char *p = strchrnul(s, '\'');
7048 /* print 'xxxx', possibly just '' */
7049 printf("'%.*s'", (int)(p - s), s);
7050 if (*p == '\0')
7051 break;
7052 s = p;
7053 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007054 /* s points to '; print "'''...'''" */
7055 putchar('"');
7056 do putchar('\''); while (*++s == '\'');
7057 putchar('"');
7058 } while (*s);
7059}
7060
Denys Vlasenko295fef82009-06-03 12:47:26 +02007061#if !ENABLE_HUSH_LOCAL
7062#define helper_export_local(argv, exp, lvl) \
7063 helper_export_local(argv, exp)
7064#endif
7065static void helper_export_local(char **argv, int exp, int lvl)
7066{
7067 do {
7068 char *name = *argv;
7069
7070 /* So far we do not check that name is valid (TODO?) */
7071
7072 if (strchr(name, '=') == NULL) {
7073 struct variable *var;
7074
7075 var = get_local_var(name);
7076 if (exp == -1) { /* unexporting? */
7077 /* export -n NAME (without =VALUE) */
7078 if (var) {
7079 var->flg_export = 0;
7080 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
7081 unsetenv(name);
7082 } /* else: export -n NOT_EXISTING_VAR: no-op */
7083 continue;
7084 }
7085 if (exp == 1) { /* exporting? */
7086 /* export NAME (without =VALUE) */
7087 if (var) {
7088 var->flg_export = 1;
7089 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
7090 putenv(var->varstr);
7091 continue;
7092 }
7093 }
7094 /* Exporting non-existing variable.
7095 * bash does not put it in environment,
7096 * but remembers that it is exported,
7097 * and does put it in env when it is set later.
7098 * We just set it to "" and export. */
7099 /* Or, it's "local NAME" (without =VALUE).
7100 * bash sets the value to "". */
7101 name = xasprintf("%s=", name);
7102 } else {
7103 /* (Un)exporting/making local NAME=VALUE */
7104 name = xstrdup(name);
7105 }
7106 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
7107 } while (*++argv);
7108}
7109
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007110static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007111{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00007112 unsigned opt_unexport;
7113
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02007114#if ENABLE_HUSH_EXPORT_N
7115 /* "!": do not abort on errors */
7116 opt_unexport = getopt32(argv, "!n");
7117 if (opt_unexport == (uint32_t)-1)
7118 return EXIT_FAILURE;
7119 argv += optind;
7120#else
7121 opt_unexport = 0;
7122 argv++;
7123#endif
7124
7125 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007126 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007127 if (e) {
7128 while (*e) {
7129#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007130 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007131#else
7132 /* ash emits: export VAR='VAL'
7133 * bash: declare -x VAR="VAL"
7134 * we follow ash example */
7135 const char *s = *e++;
7136 const char *p = strchr(s, '=');
7137
7138 if (!p) /* wtf? take next variable */
7139 continue;
7140 /* export var= */
7141 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007142 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007143 putchar('\n');
7144#endif
7145 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007146 /*fflush(stdout); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007147 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007148 return EXIT_SUCCESS;
7149 }
7150
Denys Vlasenko295fef82009-06-03 12:47:26 +02007151 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007152
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007153 return EXIT_SUCCESS;
7154}
7155
Denys Vlasenko295fef82009-06-03 12:47:26 +02007156#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007157static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007158{
7159 if (G.func_nest_level == 0) {
7160 bb_error_msg("%s: not in a function", argv[0]);
7161 return EXIT_FAILURE; /* bash compat */
7162 }
7163 helper_export_local(argv, 0, G.func_nest_level);
7164 return EXIT_SUCCESS;
7165}
7166#endif
7167
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007168static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007169{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007170 int sig;
7171 char *new_cmd;
7172
7173 if (!G.traps)
7174 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7175
7176 argv++;
7177 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007178 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007179 /* No args: print all trapped */
7180 for (i = 0; i < NSIG; ++i) {
7181 if (G.traps[i]) {
7182 printf("trap -- ");
7183 print_escaped(G.traps[i]);
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +02007184 /* note: bash adds "SIG", but only if invoked
7185 * as "bash". If called as "sh", or if set -o posix,
7186 * then it prints short signal names.
7187 * We are printing short names: */
7188 printf(" %s\n", get_signame(i));
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007189 }
7190 }
7191 /*fflush(stdout); - done after each builtin anyway */
7192 return EXIT_SUCCESS;
7193 }
7194
7195 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007196 /* If first arg is a number: reset all specified signals */
7197 sig = bb_strtou(*argv, NULL, 10);
7198 if (errno == 0) {
7199 int ret;
7200 process_sig_list:
7201 ret = EXIT_SUCCESS;
7202 while (*argv) {
7203 sig = get_signum(*argv++);
7204 if (sig < 0 || sig >= NSIG) {
7205 ret = EXIT_FAILURE;
7206 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007207 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007208 continue;
7209 }
7210
7211 free(G.traps[sig]);
7212 G.traps[sig] = xstrdup(new_cmd);
7213
7214 debug_printf("trap: setting SIG%s (%i) to '%s'",
7215 get_signame(sig), sig, G.traps[sig]);
7216
7217 /* There is no signal for 0 (EXIT) */
7218 if (sig == 0)
7219 continue;
7220
7221 if (new_cmd) {
7222 sigaddset(&G.blocked_set, sig);
7223 } else {
7224 /* There was a trap handler, we are removing it
7225 * (if sig has non-DFL handling,
7226 * we don't need to do anything) */
7227 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7228 continue;
7229 sigdelset(&G.blocked_set, sig);
7230 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007231 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007232 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007233 return ret;
7234 }
7235
7236 if (!argv[1]) { /* no second arg */
7237 bb_error_msg("trap: invalid arguments");
7238 return EXIT_FAILURE;
7239 }
7240
7241 /* First arg is "-": reset all specified to default */
7242 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7243 /* Everything else: set arg as signal handler
7244 * (includes "" case, which ignores signal) */
7245 if (argv[0][0] == '-') {
7246 if (argv[0][1] == '\0') { /* "-" */
7247 /* new_cmd remains NULL: "reset these sigs" */
7248 goto reset_traps;
7249 }
7250 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7251 argv++;
7252 }
7253 /* else: "-something", no special meaning */
7254 }
7255 new_cmd = *argv;
7256 reset_traps:
7257 argv++;
7258 goto process_sig_list;
7259}
7260
Mike Frysinger93cadc22009-05-27 17:06:25 -04007261/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007262static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007263{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007264 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007265
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007266 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007267 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007268 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007269
7270 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007271 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007272 type = "an alias";*/
7273#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007274 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007275 type = "a function";
7276#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007277 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007278 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007279 else if ((path = find_in_path(*argv)) != NULL)
7280 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007281 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007282 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007283 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007284 continue;
7285 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007286
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007287 printf("%s is %s\n", *argv, type);
7288 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007289 }
7290
7291 return ret;
7292}
7293
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007294#if ENABLE_HUSH_JOB
7295/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007296static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007297{
7298 int i, jobnum;
7299 struct pipe *pi;
7300
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007301 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007302 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007303
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007304 /* If they gave us no args, assume they want the last backgrounded task */
7305 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007306 for (pi = G.job_list; pi; pi = pi->next) {
7307 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007308 goto found;
7309 }
7310 }
7311 bb_error_msg("%s: no current job", argv[0]);
7312 return EXIT_FAILURE;
7313 }
7314 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7315 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7316 return EXIT_FAILURE;
7317 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007318 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007319 if (pi->jobid == jobnum) {
7320 goto found;
7321 }
7322 }
7323 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7324 return EXIT_FAILURE;
7325 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007326 /* TODO: bash prints a string representation
7327 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007328 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007329 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007330 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007331 }
7332
7333 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007334 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7335 for (i = 0; i < pi->num_cmds; i++) {
7336 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7337 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007338 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007339 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007340
7341 i = kill(- pi->pgrp, SIGCONT);
7342 if (i < 0) {
7343 if (errno == ESRCH) {
7344 delete_finished_bg_job(pi);
7345 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007346 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007347 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007348 }
7349
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007350 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007351 remove_bg_job(pi);
7352 return checkjobs_and_fg_shell(pi);
7353 }
7354 return EXIT_SUCCESS;
7355}
7356#endif
7357
7358#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007359static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007360{
7361 const struct built_in_command *x;
7362
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007363 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007364 "Built-in commands:\n"
7365 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007366 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7367 if (x->descr)
7368 printf("%s\t%s\n", x->cmd, x->descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007369 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007370 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007371 return EXIT_SUCCESS;
7372}
7373#endif
7374
7375#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007376static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007377{
7378 struct pipe *job;
7379 const char *status_string;
7380
Denis Vlasenko87a86552008-07-29 19:43:10 +00007381 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007382 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007383 status_string = "Stopped";
7384 else
7385 status_string = "Running";
7386
7387 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7388 }
7389 return EXIT_SUCCESS;
7390}
7391#endif
7392
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007393#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007394static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007395{
7396 void *p;
7397 unsigned long l;
7398
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007399# ifdef M_TRIM_THRESHOLD
Denys Vlasenko27726cb2009-09-12 14:48:33 +02007400 /* Optional. Reduces probability of false positives */
7401 malloc_trim(0);
Denys Vlasenkoc0836532009-10-19 13:13:06 +02007402# endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007403 /* Crude attempt to find where "free memory" starts,
7404 * sans fragmentation. */
7405 p = malloc(240);
7406 l = (unsigned long)p;
7407 free(p);
7408 p = malloc(3400);
7409 if (l < (unsigned long)p) l = (unsigned long)p;
7410 free(p);
7411
7412 if (!G.memleak_value)
7413 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007414
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007415 l -= G.memleak_value;
7416 if ((long)l < 0)
7417 l = 0;
7418 l /= 1024;
7419 if (l > 127)
7420 l = 127;
7421
7422 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7423 return l;
7424}
7425#endif
7426
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007427static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007428{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007429 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007430 return EXIT_SUCCESS;
7431}
7432
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007433static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007434{
7435 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007436 const char *name = "REPLY";
7437
7438 if (argv[1]) {
7439 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007440 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7441 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007442 if (!is_well_formed_var_name(name, '\0')) {
7443 /* Mimic bash message */
7444 bb_error_msg("read: '%s': not a valid identifier", name);
7445 return 1;
7446 }
7447 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007448
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007449//TODO: bash unbackslashes input, splits words and puts them in argv[i]
7450
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007451 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denys Vlasenko295fef82009-06-03 12:47:26 +02007452 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007453}
7454
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007455/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7456 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007457 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007458 * set [-abCefhmnuvx] [-o option] [argument...]
7459 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007460 * set -- [argument...]
7461 * set -o
7462 * set +o
7463 * Implementations shall support the options in both their hyphen and
7464 * plus-sign forms. These options can also be specified as options to sh.
7465 * Examples:
7466 * Write out all variables and their values: set
7467 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7468 * Turn on the -x and -v options: set -xv
7469 * Unset all positional parameters: set --
7470 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7471 * Set the positional parameters to the expansion of x, even if x expands
7472 * with a leading '-' or '+': set -- $x
7473 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007474 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007475 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007476static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007477{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007478 int n;
7479 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007480 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007481
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007482 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007483 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007484 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007485 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007486 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007487 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007488
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007489 do {
7490 if (!strcmp(arg, "--")) {
7491 ++argv;
7492 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007493 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007494 if (arg[0] != '+' && arg[0] != '-')
7495 break;
7496 for (n = 1; arg[n]; ++n)
7497 if (set_mode(arg[0], arg[n]))
7498 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007499 } while ((arg = *++argv) != NULL);
7500 /* Now argv[0] is 1st argument */
7501
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007502 if (arg == NULL)
7503 return EXIT_SUCCESS;
7504 set_argv:
7505
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007506 /* NB: G.global_argv[0] ($0) is never freed/changed */
7507 g_argv = G.global_argv;
7508 if (G.global_args_malloced) {
7509 pp = g_argv;
7510 while (*++pp)
7511 free(*pp);
7512 g_argv[1] = NULL;
7513 } else {
7514 G.global_args_malloced = 1;
7515 pp = xzalloc(sizeof(pp[0]) * 2);
7516 pp[0] = g_argv[0]; /* retain $0 */
7517 g_argv = pp;
7518 }
7519 /* This realloc's G.global_argv */
7520 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7521
7522 n = 1;
7523 while (*++pp)
7524 n++;
7525 G.global_argc = n;
7526
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007527 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007528
7529 /* Nothing known, so abort */
7530 error:
7531 bb_error_msg("set: %s: invalid option", arg);
7532 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007533}
7534
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007535static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007536{
7537 int n = 1;
7538 if (argv[1]) {
7539 n = atoi(argv[1]);
7540 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007541 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007542 if (G.global_args_malloced) {
7543 int m = 1;
7544 while (m <= n)
7545 free(G.global_argv[m++]);
7546 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007547 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007548 memmove(&G.global_argv[1], &G.global_argv[n+1],
7549 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007550 return EXIT_SUCCESS;
7551 }
7552 return EXIT_FAILURE;
7553}
7554
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007555static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007556{
Mike Frysinger93cadc22009-05-27 17:06:25 -04007557 char *arg_path;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007558 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007559 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007560#if ENABLE_HUSH_FUNCTIONS
7561 smallint sv_flg;
7562#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007563
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007564 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007565 return EXIT_FAILURE;
7566
Mike Frysinger93cadc22009-05-27 17:06:25 -04007567 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7568 input = fopen_for_read(arg_path);
7569 free(arg_path);
7570 } else
7571 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007572 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007573 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007574 return EXIT_FAILURE;
7575 }
7576 close_on_exec_on(fileno(input));
7577
Mike Frysinger885b6f22009-04-18 21:04:25 +00007578#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007579 sv_flg = G.flag_return_in_progress;
7580 /* "we are inside sourced file, ok to use return" */
7581 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007582#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007583 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007584
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007585 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007586 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007587
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007588 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007589#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007590 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007591#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007592
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007593 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007594}
7595
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007596static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007597{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007598 int rc;
7599 mode_t mask;
7600
7601 mask = umask(0);
7602 if (argv[1]) {
7603 mode_t old_mask = mask;
7604
7605 mask ^= 0777;
7606 rc = bb_parse_mode(argv[1], &mask);
7607 mask ^= 0777;
7608 if (rc == 0) {
7609 mask = old_mask;
7610 /* bash messages:
7611 * bash: umask: 'q': invalid symbolic mode operator
7612 * bash: umask: 999: octal number out of range
7613 */
7614 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007615 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007616 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007617 rc = 1;
7618 /* Mimic bash */
7619 printf("%04o\n", (unsigned) mask);
7620 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007621 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007622 umask(mask);
7623
7624 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007625}
7626
Mike Frysingerd690f682009-03-30 06:50:54 +00007627/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007628static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007629{
Mike Frysingerd690f682009-03-30 06:50:54 +00007630 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007631 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007632
Denis Vlasenko28e67962009-04-26 23:22:40 +00007633 /* "!": do not abort on errors */
7634 /* "+": stop at 1st non-option */
7635 opts = getopt32(argv, "!+vf");
7636 if (opts == (unsigned)-1)
7637 return EXIT_FAILURE;
7638 if (opts == 3) {
7639 bb_error_msg("unset: -v and -f are exclusive");
7640 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007641 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007642 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007643
7644 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007645 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007646 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007647 if (unset_local_var(*argv)) {
7648 /* unset <nonexistent_var> doesn't fail.
7649 * Error is when one tries to unset RO var.
7650 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007651 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007652 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007653 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007654#if ENABLE_HUSH_FUNCTIONS
7655 else {
7656 unset_func(*argv);
7657 }
7658#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007659 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007660 }
7661 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007662}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007663
Mike Frysinger56bdea12009-03-28 20:01:58 +00007664/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007665static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00007666{
7667 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007668 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007669
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007670 if (*++argv == NULL) {
7671 /* Don't care about wait results */
7672 /* Note 1: must wait until there are no more children */
7673 /* Note 2: must be interruptible */
7674 /* Examples:
7675 * $ sleep 3 & sleep 6 & wait
7676 * [1] 30934 sleep 3
7677 * [2] 30935 sleep 6
7678 * [1] Done sleep 3
7679 * [2] Done sleep 6
7680 * $ sleep 3 & sleep 6 & wait
7681 * [1] 30936 sleep 3
7682 * [2] 30937 sleep 6
7683 * [1] Done sleep 3
7684 * ^C <-- after ~4 sec from keyboard
7685 * $
7686 */
7687 sigaddset(&G.blocked_set, SIGCHLD);
7688 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7689 while (1) {
7690 checkjobs(NULL);
7691 if (errno == ECHILD)
7692 break;
7693 /* Wait for SIGCHLD or any other signal of interest */
7694 /* sigtimedwait with infinite timeout: */
7695 sig = sigwaitinfo(&G.blocked_set, NULL);
7696 if (sig > 0) {
7697 sig = check_and_run_traps(sig);
7698 if (sig && sig != SIGCHLD) { /* see note 2 */
7699 ret = 128 + sig;
7700 break;
7701 }
7702 }
7703 }
7704 sigdelset(&G.blocked_set, SIGCHLD);
7705 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7706 return ret;
7707 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007708
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007709 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007710 while (*argv) {
7711 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007712 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007713 /* mimic bash message */
7714 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007715 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007716 }
7717 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007718 if (WIFSIGNALED(status))
7719 ret = 128 + WTERMSIG(status);
7720 else if (WIFEXITED(status))
7721 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007722 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007723 ret = EXIT_FAILURE;
7724 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007725 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007726 ret = 127;
7727 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007728 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007729 }
7730
7731 return ret;
7732}
7733
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007734#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7735static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7736{
7737 if (argv[1]) {
7738 def = bb_strtou(argv[1], NULL, 10);
7739 if (errno || def < def_min || argv[2]) {
7740 bb_error_msg("%s: bad arguments", argv[0]);
7741 def = UINT_MAX;
7742 }
7743 }
7744 return def;
7745}
7746#endif
7747
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007748#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007749static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007750{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007751 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007752 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007753 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007754 return EXIT_SUCCESS; /* bash compat */
7755 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007756 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007757
7758 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7759 if (depth == UINT_MAX)
7760 G.flag_break_continue = BC_BREAK;
7761 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007762 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007763
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007764 return EXIT_SUCCESS;
7765}
7766
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007767static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007768{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007769 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7770 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007771}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007772#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007773
7774#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007775static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007776{
7777 int rc;
7778
7779 if (G.flag_return_in_progress != -1) {
7780 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7781 return EXIT_FAILURE; /* bash compat */
7782 }
7783
7784 G.flag_return_in_progress = 1;
7785
7786 /* bash:
7787 * out of range: wraps around at 256, does not error out
7788 * non-numeric param:
7789 * f() { false; return qwe; }; f; echo $?
7790 * bash: return: qwe: numeric argument required <== we do this
7791 * 255 <== we also do this
7792 */
7793 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7794 return rc;
7795}
7796#endif