blob: a02a4874f88d526427adb3a7772727e5c9b1628f [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 */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000081#include <glob.h>
82/* #include <dmalloc.h> */
83#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000084# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000085#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000086#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000087#include "match.h"
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000088#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020089# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000090#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000091
Denis Vlasenko1943aec2009-04-09 14:15:57 +000092
Denys Vlasenko8d7be232009-05-25 16:38:32 +020093/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000094#define LEAK_HUNTING 0
95#define BUILD_AS_NOMMU 0
96/* Enable/disable sanity checks. Ok to enable in production,
97 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
98 * Keeping 1 for now even in released versions.
99 */
100#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200101/* Slightly bigger (+200 bytes), but faster hush.
102 * So far it only enables a trick with counting SIGCHLDs and forks,
103 * which allows us to do fewer waitpid's.
104 * (we can detect a case where neither forks were done nor SIGCHLDs happened
105 * and therefore waitpid will return the same result as last time)
106 */
107#define ENABLE_HUSH_FAST 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +0000108
109
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000110#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000111# undef BB_MMU
112# undef USE_FOR_NOMMU
113# undef USE_FOR_MMU
114# define BB_MMU 0
115# define USE_FOR_NOMMU(...) __VA_ARGS__
116# define USE_FOR_MMU(...)
117#endif
118
Denis Vlasenko61befda2008-11-25 01:36:03 +0000119#if defined SINGLE_APPLET_MAIN
120/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000121# undef CONFIG_FEATURE_SH_STANDALONE
122# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000123# undef IF_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000124# define IF_FEATURE_SH_STANDALONE(...)
125# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denys Vlasenko673e9452009-05-27 14:39:35 +0200126# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko61befda2008-11-25 01:36:03 +0000127#endif
128
Denis Vlasenko05743d72008-02-10 12:10:08 +0000129#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000130# undef ENABLE_FEATURE_EDITING
131# define ENABLE_FEATURE_EDITING 0
132# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
133# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000134#endif
135
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000136/* Do we support ANY keywords? */
137#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000138# define HAS_KEYWORDS 1
139# define IF_HAS_KEYWORDS(...) __VA_ARGS__
140# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000141#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000142# define HAS_KEYWORDS 0
143# define IF_HAS_KEYWORDS(...)
144# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000145#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000146
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000147/* If you comment out one of these below, it will be #defined later
148 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000149#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000150/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000151#define debug_printf_parse(...) do {} while (0)
152#define debug_print_tree(a, b) do {} while (0)
153#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000154#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000155#define debug_printf_jobs(...) do {} while (0)
156#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000157#define debug_printf_glob(...) do {} while (0)
158#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000159#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000160#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000161
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000162#define ERR_PTR ((void*)(long)1)
163
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000164#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000165
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000166#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000167
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200168struct variable;
169
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000170static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
171
172/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000173 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000174 */
175#if !BB_MMU
176typedef struct nommu_save_t {
177 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200178 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000179 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000180 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000181} nommu_save_t;
182#endif
183
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000184typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000185 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000186#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000187 RES_IF ,
188 RES_THEN ,
189 RES_ELIF ,
190 RES_ELSE ,
191 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000192#endif
193#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000194 RES_FOR ,
195 RES_WHILE ,
196 RES_UNTIL ,
197 RES_DO ,
198 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000199#endif
200#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000201 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000202#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000203#if ENABLE_HUSH_CASE
204 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200205 /* three pseudo-keywords support contrived "case" syntax: */
206 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
207 RES_MATCH , /* "word)" */
208 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000209 RES_ESAC ,
210#endif
211 RES_XXXX ,
212 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000213} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000214
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000215typedef struct o_string {
216 char *data;
217 int length; /* position where data is appended */
218 int maxlen;
219 /* Protect newly added chars against globbing
220 * (by prepending \ to *, ?, [, \) */
221 smallint o_escape;
222 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000223 /* At least some part of the string was inside '' or "",
224 * possibly empty one: word"", wo''rd etc. */
225 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000226 smallint has_empty_slot;
227 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
228} o_string;
229enum {
230 MAYBE_ASSIGNMENT = 0,
231 DEFINITELY_ASSIGNMENT = 1,
232 NOT_ASSIGNMENT = 2,
233 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
234};
235/* Used for initialization: o_string foo = NULL_O_STRING; */
236#define NULL_O_STRING { NULL }
237
238/* I can almost use ordinary FILE*. Is open_memstream() universally
239 * available? Where is it documented? */
240typedef struct in_str {
241 const char *p;
242 /* eof_flag=1: last char in ->p is really an EOF */
243 char eof_flag; /* meaningless if ->p == NULL */
244 char peek_buf[2];
245#if ENABLE_HUSH_INTERACTIVE
246 smallint promptme;
247 smallint promptmode; /* 0: PS1, 1: PS2 */
248#endif
249 FILE *file;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200250 int (*get) (struct in_str *) FAST_FUNC;
251 int (*peek) (struct in_str *) FAST_FUNC;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000252} in_str;
253#define i_getch(input) ((input)->get(input))
254#define i_peek(input) ((input)->peek(input))
255
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200256/* The descrip member of this structure is only used to make
257 * debugging output pretty */
258static const struct {
259 int mode;
260 signed char default_fd;
261 char descrip[3];
262} redir_table[] = {
263 { O_RDONLY, 0, "<" },
264 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
265 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
266 { O_CREAT|O_RDWR, 1, "<>" },
267 { O_RDONLY, 0, "<<" },
268/* Should not be needed. Bogus default_fd helps in debugging */
269/* { O_RDONLY, 77, "<<" }, */
270};
271
Eric Andersen25f27032001-04-26 23:22:31 +0000272struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000273 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000274 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000275 int rd_fd; /* fd to redirect */
276 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
277 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000278 smallint rd_type; /* (enum redir_type) */
279 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000280 * and subsequently heredoc itself; and rd_dup is a bitmask:
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200281 * bit 0: do we need to trim leading tabs?
282 * bit 1: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000283 */
Eric Andersen25f27032001-04-26 23:22:31 +0000284};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000285typedef enum redir_type {
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200286 REDIRECT_INPUT = 0,
287 REDIRECT_OVERWRITE = 1,
288 REDIRECT_APPEND = 2,
289 REDIRECT_IO = 3,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000290 REDIRECT_HEREDOC = 4,
Denys Vlasenko764b2f02009-06-07 16:05:04 +0200291 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000292
293 REDIRFD_CLOSE = -3,
294 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000295 REDIRFD_TO_FILE = -1,
296 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000297
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000298 HEREDOC_SKIPTABS = 1,
299 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000300} redir_type;
301
Eric Andersen25f27032001-04-26 23:22:31 +0000302
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000303struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000304 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000305 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000306 smallint is_stopped; /* is the command currently running? */
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200307 smallint cmd_type; /* CMD_xxx */
308#define CMD_NORMAL 0
309#define CMD_SUBSHELL 1
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200310
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200311/* used for "[[ EXPR ]]" */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200312#if ENABLE_HUSH_BASH_COMPAT
313# define CMD_SINGLEWORD_NOGLOB 2
Denis Vlasenkoed055212009-04-11 10:37:10 +0000314#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200315
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200316/* used for "export noglob=* glob* a=`echo a b`" */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +0200317//#define CMD_SINGLEWORD_NOGLOB_COND 3
Denys Vlasenko9ca656b2009-06-10 13:39:35 +0200318// It is hard to implement correctly, it adds significant amounts of tricky code,
319// and all this is only useful for really obscure export statements
320// almost nobody would use anyway. #ifdef CMD_SINGLEWORD_NOGLOB_COND
321// guards the code which implements it, but I have doubts it works
322// in all cases (especially with mixed globbed/non-globbed arguments)
323
324#if ENABLE_HUSH_FUNCTIONS
325# define CMD_FUNCDEF 3
326#endif
327
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200328 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
329 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000330#if !BB_MMU
331 char *group_as_string;
332#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000333#if ENABLE_HUSH_FUNCTIONS
334 struct function *child_func;
335/* This field is used to prevent a bug here:
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200336 * while...do f1() {a;}; f1; f1() {b;}; f1; done
Denis Vlasenkoed055212009-04-11 10:37:10 +0000337 * When we execute "f1() {a;}" cmd, we create new function and clear
338 * cmd->group, cmd->group_as_string, cmd->argv[0].
Denys Vlasenko9d617c42009-06-09 18:40:52 +0200339 * When we execute "f1() {b;}", we notice that f1 exists,
340 * and that its "parent cmd" struct is still "alive",
Denis Vlasenkoed055212009-04-11 10:37:10 +0000341 * we put those fields back into cmd->xxx
342 * (struct function has ->parent_cmd ptr to facilitate that).
343 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
344 * Without this trick, loop would execute a;b;b;b;...
345 * instead of correct sequence a;b;a;b;...
346 * When command is freed, it severs the link
347 * (sets ->child_func->parent_cmd to NULL).
348 */
349#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000350 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000351/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
352 * and on execution these are substituted with their values.
353 * Substitution can make _several_ words out of one argv[n]!
354 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000355 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000356 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000357 struct redir_struct *redirects; /* I/O redirections */
358};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000359/* Is there anything in this command at all? */
360#define IS_NULL_CMD(cmd) \
361 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
362
Eric Andersen25f27032001-04-26 23:22:31 +0000363
364struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000365 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000366 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000367 int alive_cmds; /* number of commands running (not exited) */
368 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000369#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000370 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000371 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000372 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000373#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000374 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000375 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000376 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
377 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000378};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000379typedef enum pipe_style {
380 PIPE_SEQ = 1,
381 PIPE_AND = 2,
382 PIPE_OR = 3,
383 PIPE_BG = 4,
384} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000385/* Is there anything in this pipe at all? */
386#define IS_NULL_PIPE(pi) \
387 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000388
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000389/* This holds pointers to the various results of parsing */
390struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000391 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000392 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000393 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000394 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000395 /* last command in pipe (being constructed right now) */
396 struct command *command;
397 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000398 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000399#if !BB_MMU
400 o_string as_string;
401#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000402#if HAS_KEYWORDS
403 smallint ctx_res_w;
404 smallint ctx_inverted; /* "! cmd | cmd" */
405#if ENABLE_HUSH_CASE
406 smallint ctx_dsemicolon; /* ";;" seen */
407#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000408 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
409 int old_flag;
410 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000411 * example: "if pipe1; pipe2; then pipe3; fi"
412 * when we see "if" or "then", we malloc and copy current context,
413 * and make ->stack point to it. then we parse pipeN.
414 * when closing "then" / fi" / whatever is found,
415 * we move list_head into ->stack->command->group,
416 * copy ->stack into current context, and delete ->stack.
417 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000418 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000419 struct parse_context *stack;
420#endif
421};
422
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000423/* On program start, environ points to initial environment.
424 * putenv adds new pointers into it, unsetenv removes them.
425 * Neither of these (de)allocates the strings.
426 * setenv allocates new strings in malloc space and does putenv,
427 * and thus setenv is unusable (leaky) for shell's purposes */
428#define setenv(...) setenv_is_leaky_dont_use()
429struct variable {
430 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000431 char *varstr; /* points to "name=" portion */
Denys Vlasenko295fef82009-06-03 12:47:26 +0200432#if ENABLE_HUSH_LOCAL
433 unsigned func_nest_level;
434#endif
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000435 int max_len; /* if > 0, name is part of initial env; else name is malloced */
436 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000437 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000438};
439
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000440enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000441 BC_BREAK = 1,
442 BC_CONTINUE = 2,
443};
444
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000445#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000446struct function {
447 struct function *next;
448 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000449 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000450 struct pipe *body;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000451#if !BB_MMU
452 char *body_as_string;
453#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000454};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000455#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000456
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000457
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000458/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000459/* Sorted roughly by size (smaller offsets == smaller code) */
460struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000461 /* interactive_fd != 0 means we are an interactive shell.
462 * If we are, then saved_tty_pgrp can also be != 0, meaning
463 * that controlling tty is available. With saved_tty_pgrp == 0,
464 * job control still works, but terminal signals
465 * (^C, ^Z, ^Y, ^\) won't work at all, and background
466 * process groups can only be created with "cmd &".
467 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
468 * to give tty to the foreground process group,
469 * and will take it back when the group is stopped (^Z)
470 * or killed (^C).
471 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000472#if ENABLE_HUSH_INTERACTIVE
473 /* 'interactive_fd' is a fd# open to ctty, if we have one
474 * _AND_ if we decided to act interactively */
475 int interactive_fd;
476 const char *PS1;
477 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000478# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000479#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000480# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481#endif
482#if ENABLE_FEATURE_EDITING
483 line_input_t *line_input_state;
484#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000485 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000486 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000487#if ENABLE_HUSH_JOB
488 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000489 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000490 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000491 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400492# define G_saved_tty_pgrp (G.saved_tty_pgrp)
493#else
494# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000495#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000496 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000497#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000498 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000499#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000500#if ENABLE_HUSH_FUNCTIONS
501 /* 0: outside of a function (or sourced file)
502 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000503 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000504 */
505 smallint flag_return_in_progress;
506#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000507 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000508 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000509 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000510 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000511 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000512 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000513 /* how many non-NULL argv's we have. NB: $# + 1 */
514 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000515 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000516#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000517 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000518#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000519#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000520 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000521 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000522#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000523 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000524 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000525 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000526 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000527#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000528 struct function *top_func;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200529# if ENABLE_HUSH_LOCAL
530 struct variable **shadowed_vars_pp;
531 unsigned func_nest_level;
532# endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000533#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000534 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200535#if ENABLE_HUSH_FAST
536 unsigned count_SIGCHLD;
537 unsigned handled_SIGCHLD;
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +0200538 smallint we_have_children;
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200539#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000540 /* which signals have non-DFL handler (even with no traps set)? */
541 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000542 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000543 sigset_t blocked_set;
544 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000545#if HUSH_DEBUG
546 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000547 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000548#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000549 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000550};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000551#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000552/* Not #defining name to G.name - this quickly gets unwieldy
553 * (too many defines). Also, I actually prefer to see when a variable
554 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000555#define INIT_G() do { \
556 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
557} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000558
559
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000560/* Function prototypes for builtins */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200561static int builtin_cd(char **argv) FAST_FUNC;
562static int builtin_echo(char **argv) FAST_FUNC;
563static int builtin_eval(char **argv) FAST_FUNC;
564static int builtin_exec(char **argv) FAST_FUNC;
565static int builtin_exit(char **argv) FAST_FUNC;
566static int builtin_export(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000567#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200568static int builtin_fg_bg(char **argv) FAST_FUNC;
569static int builtin_jobs(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000570#endif
571#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200572static int builtin_help(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000573#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200574#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200575static int builtin_local(char **argv) FAST_FUNC;
Denys Vlasenko295fef82009-06-03 12:47:26 +0200576#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000577#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200578static int builtin_memleak(char **argv) FAST_FUNC;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000579#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200580static int builtin_pwd(char **argv) FAST_FUNC;
581static int builtin_read(char **argv) FAST_FUNC;
582static int builtin_set(char **argv) FAST_FUNC;
583static int builtin_shift(char **argv) FAST_FUNC;
584static int builtin_source(char **argv) FAST_FUNC;
585static int builtin_test(char **argv) FAST_FUNC;
586static int builtin_trap(char **argv) FAST_FUNC;
587static int builtin_type(char **argv) FAST_FUNC;
588static int builtin_true(char **argv) FAST_FUNC;
589static int builtin_umask(char **argv) FAST_FUNC;
590static int builtin_unset(char **argv) FAST_FUNC;
591static int builtin_wait(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000592#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200593static int builtin_break(char **argv) FAST_FUNC;
594static int builtin_continue(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000595#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000596#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200597static int builtin_return(char **argv) FAST_FUNC;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000598#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000599
600/* Table of built-in functions. They can be forked or not, depending on
601 * context: within pipes, they fork. As simple commands, they do not.
602 * When used in non-forking context, they can change global variables
603 * in the parent shell process. If forked, of course they cannot.
604 * For example, 'unset foo | whatever' will parse and run, but foo will
605 * still be set at the end. */
606struct built_in_command {
607 const char *cmd;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +0200608 int (*function)(char **argv) FAST_FUNC;
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000609#if ENABLE_HUSH_HELP
610 const char *descr;
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200611# define BLTIN(cmd, func, help) { cmd, func, help }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000612#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200613# define BLTIN(cmd, func, help) { cmd, func }
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000614#endif
615};
616
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200617static const struct built_in_command bltins1[] = {
618 BLTIN("." , builtin_source , "Run commands in a file"),
619 BLTIN(":" , builtin_true , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000620#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200621 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000622#endif
623#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200624 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000625#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200626 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000627#if ENABLE_HUSH_LOOPS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200628 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000629#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200630 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
631 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
632 BLTIN("exit" , builtin_exit , "Exit"),
633 BLTIN("export" , builtin_export , "Set environment variables"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000634#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200635 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000636#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000637#if ENABLE_HUSH_HELP
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200638 BLTIN("help" , builtin_help , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000639#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000640#if ENABLE_HUSH_JOB
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200641 BLTIN("jobs" , builtin_jobs , "List jobs"),
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000642#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +0200643#if ENABLE_HUSH_LOCAL
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200644 BLTIN("local" , builtin_local , "Set local variables"),
Denys Vlasenko295fef82009-06-03 12:47:26 +0200645#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000646#if HUSH_DEBUG
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200647 BLTIN("memleak" , builtin_memleak , NULL),
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000648#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200649 BLTIN("read" , builtin_read , "Input into variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000650#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200651 BLTIN("return" , builtin_return , "Return from a function"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000652#endif
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +0200653 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
654 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
655 BLTIN("trap" , builtin_trap , "Trap signals"),
656 BLTIN("type" , builtin_type , "Write a description of command type"),
657// BLTIN("ulimit" , builtin_ulimit , "Control resource limits"),
658 BLTIN("umask" , builtin_umask , "Set file creation mask"),
659 BLTIN("unset" , builtin_unset , "Unset variables"),
660 BLTIN("wait" , builtin_wait , "Wait for process"),
661};
662/* For now, echo and test are unconditionally enabled.
663 * Maybe make it configurable? */
664static const struct built_in_command bltins2[] = {
665 BLTIN("[" , builtin_test , NULL),
666 BLTIN("echo" , builtin_echo , NULL),
667 BLTIN("pwd" , builtin_pwd , NULL),
668 BLTIN("test" , builtin_test , NULL),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000669};
670
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000671
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000672/* Debug printouts.
673 */
674#if HUSH_DEBUG
675/* prevent disasters with G.debug_indent < 0 */
676# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
677# define debug_enter() (G.debug_indent++)
678# define debug_leave() (G.debug_indent--)
679#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200680# define indent() ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000681# define debug_enter() ((void)0)
682# define debug_leave() ((void)0)
683#endif
684
685#ifndef debug_printf
686# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
687#endif
688
689#ifndef debug_printf_parse
690# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
691#endif
692
693#ifndef debug_printf_exec
694#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
695#endif
696
697#ifndef debug_printf_env
698# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
699#endif
700
701#ifndef debug_printf_jobs
702# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
703# define DEBUG_JOBS 1
704#else
705# define DEBUG_JOBS 0
706#endif
707
708#ifndef debug_printf_expand
709# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
710# define DEBUG_EXPAND 1
711#else
712# define DEBUG_EXPAND 0
713#endif
714
715#ifndef debug_printf_glob
716# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
717# define DEBUG_GLOB 1
718#else
719# define DEBUG_GLOB 0
720#endif
721
722#ifndef debug_printf_list
723# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
724#endif
725
726#ifndef debug_printf_subst
727# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
728#endif
729
730#ifndef debug_printf_clean
731# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
732# define DEBUG_CLEAN 1
733#else
734# define DEBUG_CLEAN 0
735#endif
736
737#if DEBUG_EXPAND
738static void debug_print_strings(const char *prefix, char **vv)
739{
740 indent();
741 fprintf(stderr, "%s:\n", prefix);
742 while (*vv)
743 fprintf(stderr, " '%s'\n", *vv++);
744}
745#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200746# define debug_print_strings(prefix, vv) ((void)0)
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000747#endif
748
749
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000750/* Leak hunting. Use hush_leaktool.sh for post-processing.
751 */
752#if LEAK_HUNTING
753static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000754{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000755 void *ptr = xmalloc((size + 0xff) & ~0xff);
756 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
757 return ptr;
758}
759static void *xxrealloc(int lineno, void *ptr, size_t size)
760{
761 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
762 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
763 return ptr;
764}
765static char *xxstrdup(int lineno, const char *str)
766{
767 char *ptr = xstrdup(str);
768 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
769 return ptr;
770}
771static void xxfree(void *ptr)
772{
773 fdprintf(2, "free %p\n", ptr);
774 free(ptr);
775}
776#define xmalloc(s) xxmalloc(__LINE__, s)
777#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
778#define xstrdup(s) xxstrdup(__LINE__, s)
779#define free(p) xxfree(p)
780#endif
781
782
783/* Syntax and runtime errors. They always abort scripts.
784 * In interactive use they usually discard unparsed and/or unexecuted commands
785 * and return to the prompt.
786 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
787 */
788#if HUSH_DEBUG < 2
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000789# define die_if_script(lineno, fmt...) die_if_script(fmt)
790# define syntax_error(lineno, msg) syntax_error(msg)
791# define syntax_error_at(lineno, msg) syntax_error_at(msg)
792# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
793# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
794# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000795#endif
796
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000797static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000798{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000799 va_list p;
800
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000801#if HUSH_DEBUG >= 2
802 bb_error_msg("hush.c:%u", lineno);
803#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000804 va_start(p, fmt);
805 bb_verror_msg(fmt, p, NULL);
806 va_end(p);
807 if (!G_interactive_fd)
808 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000809}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000810
811static void syntax_error(unsigned lineno, const char *msg)
812{
813 if (msg)
814 die_if_script(lineno, "syntax error: %s", msg);
815 else
816 die_if_script(lineno, "syntax error", NULL);
817}
818
819static void syntax_error_at(unsigned lineno, const char *msg)
820{
821 die_if_script(lineno, "syntax error at '%s'", msg);
822}
823
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400824static void syntax_error_unterm_str(unsigned lineno, const char *s)
825{
826 die_if_script(lineno, "syntax error: unterminated %s", s);
827}
828
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000829/* It so happens that all such cases are totally fatal
830 * even if shell is interactive: EOF while looking for closing
831 * delimiter. There is nowhere to read stuff from after that,
832 * it's EOF! The only choice is to terminate.
833 */
834static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000835static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000836{
Mike Frysinger6a46ab82009-06-01 14:14:36 -0400837 char msg[2] = { ch, '\0' };
838 syntax_error_unterm_str(lineno, msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000839 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000840}
841
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200842static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000843{
844 char msg[2];
845 msg[0] = ch;
846 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200847 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000848}
849
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000850#if HUSH_DEBUG < 2
851# undef die_if_script
852# undef syntax_error
853# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000854# undef syntax_error_unterm_ch
855# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000856# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000857#else
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000858# define die_if_script(fmt...) die_if_script(__LINE__, fmt)
859# define syntax_error(msg) syntax_error(__LINE__, msg)
860# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
861# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
862# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
863# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000864#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000865
Denis Vlasenko552433b2009-04-04 19:29:21 +0000866
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000867#if ENABLE_HUSH_INTERACTIVE
868static void cmdedit_update_prompt(void);
869#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +0200870# define cmdedit_update_prompt() ((void)0)
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000871#endif
872
873
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000874/* Utility functions
875 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000876static int glob_needed(const char *s)
877{
878 while (*s) {
879 if (*s == '\\')
880 s++;
881 if (*s == '*' || *s == '[' || *s == '?')
882 return 1;
883 s++;
884 }
885 return 0;
886}
887
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000888static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000889{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000890 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000891 return 0;
892 s++;
893 while (isalnum(*s) || *s == '_')
894 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000895 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000896}
897
Denis Vlasenko55789c62008-06-18 16:30:42 +0000898/* Replace each \x with x in place, return ptr past NUL. */
899static char *unbackslash(char *src)
900{
901 char *dst = src;
902 while (1) {
903 if (*src == '\\')
904 src++;
905 if ((*dst++ = *src++) == '\0')
906 break;
907 }
908 return dst;
909}
910
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000911static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000912{
913 int i;
914 unsigned count1;
915 unsigned count2;
916 char **v;
917
918 v = strings;
919 count1 = 0;
920 if (v) {
921 while (*v) {
922 count1++;
923 v++;
924 }
925 }
926 count2 = 0;
927 v = add;
928 while (*v) {
929 count2++;
930 v++;
931 }
932 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
933 v[count1 + count2] = NULL;
934 i = count2;
935 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000936 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000937 return v;
938}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000939#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000940static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
941{
942 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
943 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
944 return ptr;
945}
946#define add_strings_to_strings(strings, add, need_to_dup) \
947 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
948#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000949
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200950/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000951static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000952{
953 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000954 v[0] = add;
955 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000956 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000957}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000958#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000959static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
960{
961 char **ptr = add_string_to_strings(strings, add);
962 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
963 return ptr;
964}
965#define add_string_to_strings(strings, add) \
966 xx_add_string_to_strings(__LINE__, strings, add)
967#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000968
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200969static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000970{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000971 char **v;
972
973 if (!strings)
974 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000975 v = strings;
976 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200977 free(*v);
978 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000979 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000980 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000981}
982
Denis Vlasenko76d50412008-06-10 16:19:39 +0000983
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000984/* Helpers for setting new $n and restoring them back
985 */
986typedef struct save_arg_t {
987 char *sv_argv0;
988 char **sv_g_argv;
989 int sv_g_argc;
990 smallint sv_g_malloced;
991} save_arg_t;
992
993static void save_and_replace_G_args(save_arg_t *sv, char **argv)
994{
995 int n;
996
997 sv->sv_argv0 = argv[0];
998 sv->sv_g_argv = G.global_argv;
999 sv->sv_g_argc = G.global_argc;
1000 sv->sv_g_malloced = G.global_args_malloced;
1001
1002 argv[0] = G.global_argv[0]; /* retain $0 */
1003 G.global_argv = argv;
1004 G.global_args_malloced = 0;
1005
1006 n = 1;
1007 while (*++argv)
1008 n++;
1009 G.global_argc = n;
1010}
1011
1012static void restore_G_args(save_arg_t *sv, char **argv)
1013{
1014 char **pp;
1015
1016 if (G.global_args_malloced) {
1017 /* someone ran "set -- arg1 arg2 ...", undo */
1018 pp = G.global_argv;
1019 while (*++pp) /* note: does not free $0 */
1020 free(*pp);
1021 free(G.global_argv);
1022 }
1023 argv[0] = sv->sv_argv0;
1024 G.global_argv = sv->sv_g_argv;
1025 G.global_argc = sv->sv_g_argc;
1026 G.global_args_malloced = sv->sv_g_malloced;
1027}
1028
1029
Denis Vlasenkod5762932009-03-31 11:22:57 +00001030/* Basic theory of signal handling in shell
1031 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001032 * This does not describe what hush does, rather, it is current understanding
1033 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001034 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1035 *
1036 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1037 * is finished or backgrounded. It is the same in interactive and
1038 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001039 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001040 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1041 * backgrounds (i.e. stops) or kills all members of currently running
1042 * pipe.
1043 *
1044 * Wait builtin in interruptible by signals for which user trap is set
1045 * or by SIGINT in interactive shell.
1046 *
1047 * Trap handlers will execute even within trap handlers. (right?)
1048 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001049 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001050 *
1051 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001052 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001053 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001054 * Commands which are run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001055 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001056 *
Denys Vlasenko4b7db4f2009-05-29 10:39:06 +02001057 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001058 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001059 *
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001060 * Signals which differ from SIG_DFL action
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001061 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001062 *
1063 * SIGQUIT: ignore
1064 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001065 * SIGHUP (interactive):
1066 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001067 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001068 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1069 * that all pipe members are stopped. Try this in bash:
1070 * while :; do :; done - ^Z does not background it
1071 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001072 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001073 * of the command line, show prompt. NB: ^C does not send SIGINT
1074 * to interactive shell while shell is waiting for a pipe,
1075 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001076 * Example 1: this waits 5 sec, but does not execute ls:
1077 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1078 * Example 2: this does not wait and does not execute ls:
1079 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1080 * Example 3: this does not wait 5 sec, but executes ls:
1081 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001082 *
1083 * (What happens to signals which are IGN on shell start?)
1084 * (What happens with signal mask on shell start?)
1085 *
1086 * Implementation in hush
1087 * ======================
1088 * We use in-kernel pending signal mask to determine which signals were sent.
1089 * We block all signals which we don't want to take action immediately,
1090 * i.e. we block all signals which need to have special handling as described
1091 * above, and all signals which have traps set.
1092 * After each pipe execution, we extract any pending signals via sigtimedwait()
1093 * and act on them.
1094 *
1095 * unsigned non_DFL_mask: a mask of such "special" signals
1096 * sigset_t blocked_set: current blocked signal set
1097 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001098 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001099 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001100 * "trap 'cmd' SIGxxx":
1101 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001102 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001103 * unblock signals with special interactive handling
1104 * (child shell is not interactive),
1105 * unset all traps (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001106 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001107 * POSIX says pending signal mask is cleared in child - no need to clear it.
1108 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001109 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001110 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001111 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001112 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001113 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001114enum {
1115 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001116 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001117 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001118 | (1 << SIGHUP)
1119 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001120 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001121#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001122 | (1 << SIGTTIN)
1123 | (1 << SIGTTOU)
1124 | (1 << SIGTSTP)
1125#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001126};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001127
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001128#if ENABLE_HUSH_FAST
1129static void SIGCHLD_handler(int sig UNUSED_PARAM)
1130{
1131 G.count_SIGCHLD++;
1132//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1133}
1134#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001135
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001136#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001137
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001138/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1139#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001140/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001141#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1142
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001143/* Restores tty foreground process group, and exits.
1144 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001145 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001146 * or called directly with -EXITCODE.
1147 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001148static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001149static void sigexit(int sig)
1150{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001151 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001152 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001153
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001154 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001155 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001156 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1157 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001158
1159 /* Not a signal, just exit */
1160 if (sig <= 0)
1161 _exit(- sig);
1162
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001163 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001164}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001165#else
1166
1167#define disable_restore_tty_pgrp_on_exit() ((void)0)
1168#define enable_restore_tty_pgrp_on_exit() ((void)0)
1169
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001170#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001171
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001172/* Restores tty foreground process group, and exits. */
1173static void hush_exit(int exitcode) NORETURN;
1174static void hush_exit(int exitcode)
1175{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001176 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1177 /* Prevent recursion:
1178 * trap "echo Hi; exit" EXIT; exit
1179 */
1180 char *argv[] = { NULL, G.traps[0], NULL };
1181 G.traps[0] = NULL;
1182 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001183 builtin_eval(argv);
1184 free(argv[1]);
1185 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001186
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001187#if ENABLE_HUSH_JOB
1188 fflush(NULL); /* flush all streams */
1189 sigexit(- (exitcode & 0xff));
1190#else
1191 exit(exitcode);
1192#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001193}
1194
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001195static int check_and_run_traps(int sig)
1196{
1197 static const struct timespec zero_timespec = { 0, 0 };
1198 smalluint save_rcode;
1199 int last_sig = 0;
1200
1201 if (sig)
1202 goto jump_in;
1203 while (1) {
1204 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1205 if (sig <= 0)
1206 break;
1207 jump_in:
1208 last_sig = sig;
1209 if (G.traps && G.traps[sig]) {
1210 if (G.traps[sig][0]) {
1211 /* We have user-defined handler */
1212 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1213 save_rcode = G.last_exitcode;
1214 builtin_eval(argv);
1215 free(argv[1]);
1216 G.last_exitcode = save_rcode;
1217 } /* else: "" trap, ignoring signal */
1218 continue;
1219 }
1220 /* not a trap: special action */
1221 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001222#if ENABLE_HUSH_FAST
1223 case SIGCHLD:
1224 G.count_SIGCHLD++;
1225//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1226 break;
1227#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001228 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001229 /* Builtin was ^C'ed, make it look prettier: */
1230 bb_putchar('\n');
1231 G.flag_SIGINT = 1;
1232 break;
1233#if ENABLE_HUSH_JOB
1234 case SIGHUP: {
1235 struct pipe *job;
1236 /* bash is observed to signal whole process groups,
1237 * not individual processes */
1238 for (job = G.job_list; job; job = job->next) {
1239 if (job->pgrp <= 0)
1240 continue;
1241 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1242 if (kill(- job->pgrp, SIGHUP) == 0)
1243 kill(- job->pgrp, SIGCONT);
1244 }
1245 sigexit(SIGHUP);
1246 }
1247#endif
1248 default: /* ignored: */
1249 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1250 break;
1251 }
1252 }
1253 return last_sig;
1254}
1255
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001256
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001257static const char *get_cwd(int force)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001258{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001259 if (force || G.cwd == NULL) {
1260 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1261 * we must not try to free(bb_msg_unknown) */
1262 if (G.cwd == bb_msg_unknown)
1263 G.cwd = NULL;
1264 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1265 if (!G.cwd)
1266 G.cwd = bb_msg_unknown;
1267 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001268 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001269}
1270
Denis Vlasenko83506862007-11-23 13:11:42 +00001271
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001272/*
1273 * Shell and environment variable support
1274 */
1275static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001276{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001277 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001278 struct variable *cur;
1279 int len;
1280
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001281 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001282 pp = &G.top_var;
1283 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001284 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001285 return pp;
1286 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001287 }
1288 return NULL;
1289}
1290
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001291static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001292{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001293 struct variable **pp = get_ptr_to_local_var(name);
1294 if (pp)
1295 return *pp;
1296 return NULL;
1297}
1298
1299static const char *get_local_var_value(const char *name)
1300{
1301 struct variable **pp = get_ptr_to_local_var(name);
1302 if (pp)
1303 return strchr((*pp)->varstr, '=') + 1;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001304 return NULL;
1305}
1306
1307/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001308 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001309 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001310 * 0: do not change export flag
1311 * (if creating new variable, flag will be 0)
1312 * 1: set export flag and putenv the variable
1313 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001314 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001315 */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001316#if !BB_MMU && ENABLE_HUSH_LOCAL
1317/* all params are used */
1318#elif BB_MMU && ENABLE_HUSH_LOCAL
1319#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1320 set_local_var(str, flg_export, local_lvl)
1321#elif BB_MMU && !ENABLE_HUSH_LOCAL
1322#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001323 set_local_var(str, flg_export)
Denys Vlasenko295fef82009-06-03 12:47:26 +02001324#elif !BB_MMU && !ENABLE_HUSH_LOCAL
1325#define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1326 set_local_var(str, flg_export, flg_read_only)
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001327#endif
Denys Vlasenko295fef82009-06-03 12:47:26 +02001328static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001329{
Denys Vlasenko295fef82009-06-03 12:47:26 +02001330 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001331 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001332 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001333 int name_len;
1334
Denis Vlasenko950bd722009-04-21 11:23:56 +00001335 eq_sign = strchr(str, '=');
1336 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001337 free(str);
1338 return -1;
1339 }
1340
Denis Vlasenko950bd722009-04-21 11:23:56 +00001341 name_len = eq_sign - str + 1; /* including '=' */
Denys Vlasenko295fef82009-06-03 12:47:26 +02001342 var_pp = &G.top_var;
1343 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001344 if (strncmp(cur->varstr, str, name_len) != 0) {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001345 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001346 continue;
1347 }
1348 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001349 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001350#if !BB_MMU
1351 if (!flg_read_only)
1352#endif
1353 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001354 free(str);
1355 return -1;
1356 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001357 if (flg_export == -1) { // "&& cur->flg_export" ?
Denis Vlasenko950bd722009-04-21 11:23:56 +00001358 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1359 *eq_sign = '\0';
1360 unsetenv(str);
1361 *eq_sign = '=';
1362 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001363#if ENABLE_HUSH_LOCAL
1364 if (cur->func_nest_level < local_lvl) {
1365 /* New variable is declared as local,
1366 * and existing one is global, or local
1367 * from enclosing function.
1368 * Remove and save old one: */
1369 *var_pp = cur->next;
1370 cur->next = *G.shadowed_vars_pp;
1371 *G.shadowed_vars_pp = cur;
1372 /* bash 3.2.33(1) and exported vars:
1373 * # export z=z
1374 * # f() { local z=a; env | grep ^z; }
1375 * # f
1376 * z=a
1377 * # env | grep ^z
1378 * z=z
1379 */
1380 if (cur->flg_export)
1381 flg_export = 1;
1382 break;
1383 }
1384#endif
Denis Vlasenko950bd722009-04-21 11:23:56 +00001385 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001386 free_and_exp:
1387 free(str);
1388 goto exp;
1389 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001390 if (cur->max_len != 0) {
1391 if (cur->max_len >= strlen(str)) {
1392 /* This one is from startup env, reuse space */
1393 strcpy(cur->varstr, str);
1394 goto free_and_exp;
1395 }
1396 } else {
1397 /* max_len == 0 signifies "malloced" var, which we can
1398 * (and has to) free */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001399 free(cur->varstr);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001400 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001401 cur->max_len = 0;
1402 goto set_str_and_exp;
1403 }
1404
Denys Vlasenko295fef82009-06-03 12:47:26 +02001405 /* Not found - create new variable struct */
1406 cur = xzalloc(sizeof(*cur));
1407#if ENABLE_HUSH_LOCAL
1408 cur->func_nest_level = local_lvl;
1409#endif
1410 cur->next = *var_pp;
1411 *var_pp = cur;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001412
1413 set_str_and_exp:
1414 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001415#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001416 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001417#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001418 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001419 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001420 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001421 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1422 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001423 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001424 if (flg_export == -1) {
1425 cur->flg_export = 0;
1426 /* unsetenv was already done */
1427 } else {
1428 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1429 return putenv(cur->varstr);
1430 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001431 }
1432 return 0;
1433}
1434
Denys Vlasenko6db47842009-09-05 20:15:17 +02001435/* Used at startup and after each cd */
1436static void set_pwd_var(int exp)
1437{
1438 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1439 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1440}
1441
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001442static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001443{
1444 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001445 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001446
1447 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001448 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001449 var_pp = &G.top_var;
1450 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001451 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1452 if (cur->flg_read_only) {
1453 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001454 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001455 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001456 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001457 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1458 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001459 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1460 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001461 if (!cur->max_len)
1462 free(cur->varstr);
1463 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001464 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001465 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001466 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001467 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001468 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001469}
1470
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001471static int unset_local_var(const char *name)
1472{
1473 return unset_local_var_len(name, strlen(name));
1474}
1475
1476static void unset_vars(char **strings)
1477{
1478 char **v;
1479
1480 if (!strings)
1481 return;
1482 v = strings;
1483 while (*v) {
1484 const char *eq = strchrnul(*v, '=');
1485 unset_local_var_len(*v, (int)(eq - *v));
1486 v++;
1487 }
1488 free(strings);
1489}
1490
Mike Frysinger98c52642009-04-02 10:02:37 +00001491#if ENABLE_SH_MATH_SUPPORT
1492#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1493#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1494static char *endofname(const char *name)
1495{
1496 char *p;
1497
1498 p = (char *) name;
1499 if (!is_name(*p))
1500 return p;
1501 while (*++p) {
1502 if (!is_in_name(*p))
1503 break;
1504 }
1505 return p;
1506}
1507
1508static void arith_set_local_var(const char *name, const char *val, int flags)
1509{
1510 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001511 char *var = xasprintf("%s=%s", name, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02001512 set_local_var(var, flags, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001513}
1514#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001515
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001516
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001517/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001518 * Helpers for "var1=val1 var2=val2 cmd" feature
1519 */
1520static void add_vars(struct variable *var)
1521{
1522 struct variable *next;
1523
1524 while (var) {
1525 next = var->next;
1526 var->next = G.top_var;
1527 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001528 if (var->flg_export) {
1529 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001530 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001531 } else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02001532 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001533 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001534 var = next;
1535 }
1536}
1537
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001538static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001539{
1540 char **s;
1541 struct variable *old = NULL;
1542
1543 if (!strings)
1544 return old;
1545 s = strings;
1546 while (*s) {
1547 struct variable *var_p;
1548 struct variable **var_pp;
1549 char *eq;
1550
1551 eq = strchr(*s, '=');
1552 if (eq) {
1553 *eq = '\0';
1554 var_pp = get_ptr_to_local_var(*s);
1555 *eq = '=';
1556 if (var_pp) {
1557 /* Remove variable from global linked list */
1558 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001559 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001560 *var_pp = var_p->next;
1561 /* Add it to returned list */
1562 var_p->next = old;
1563 old = var_p;
1564 }
Denys Vlasenko295fef82009-06-03 12:47:26 +02001565 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001566 }
1567 s++;
1568 }
1569 return old;
1570}
1571
1572
1573/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001574 * in_str support
1575 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001576static int FAST_FUNC static_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001577{
1578 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001579 if (ch != '\0')
1580 return ch;
1581 i->p--;
1582 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001583}
1584
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001585static int FAST_FUNC static_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001586{
1587 return *i->p;
1588}
1589
1590#if ENABLE_HUSH_INTERACTIVE
1591
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001592static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001593{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001594 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001595 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001596 if (G.PS1 == NULL)
1597 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001598 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001599 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001600 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001601 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001602 if (G.PS2 == NULL)
1603 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001604}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001605
1606static const char* setup_prompt_string(int promptmode)
1607{
1608 const char *prompt_str;
1609 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001610 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1611 /* Set up the prompt */
1612 if (promptmode == 0) { /* PS1 */
1613 free((char*)G.PS1);
Denys Vlasenko6db47842009-09-05 20:15:17 +02001614 /* bash uses $PWD value, even if it is set by user.
1615 * It uses current dir only if PWD is unset.
1616 * We always use current dir. */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02001617 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
Mike Frysingerec2c6552009-03-28 12:24:44 +00001618 prompt_str = G.PS1;
1619 } else
1620 prompt_str = G.PS2;
1621 } else
1622 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001623 debug_printf("result '%s'\n", prompt_str);
1624 return prompt_str;
1625}
1626
1627static void get_user_input(struct in_str *i)
1628{
1629 int r;
1630 const char *prompt_str;
1631
1632 prompt_str = setup_prompt_string(i->promptmode);
1633#if ENABLE_FEATURE_EDITING
1634 /* Enable command line editing only while a command line
1635 * is actually being read */
1636 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001637 G.flag_SIGINT = 0;
1638 /* buglet: SIGINT will not make new prompt to appear _at once_,
1639 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001640 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001641 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001642 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001643 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001644 i->eof_flag = (r < 0);
1645 if (i->eof_flag) { /* EOF/error detected */
1646 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1647 G.user_input_buf[1] = '\0';
1648 }
1649#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001650 do {
1651 G.flag_SIGINT = 0;
1652 fputs(prompt_str, stdout);
1653 fflush(stdout);
1654 G.user_input_buf[0] = r = fgetc(i->file);
1655 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001656//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001657 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001658 i->eof_flag = (r == EOF);
1659#endif
1660 i->p = G.user_input_buf;
1661}
1662
1663#endif /* INTERACTIVE */
1664
1665/* This is the magic location that prints prompts
1666 * and gets data back from the user */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001667static int FAST_FUNC file_get(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001668{
1669 int ch;
1670
1671 /* If there is data waiting, eat it up */
1672 if (i->p && *i->p) {
1673#if ENABLE_HUSH_INTERACTIVE
1674 take_cached:
1675#endif
1676 ch = *i->p++;
1677 if (i->eof_flag && !*i->p)
1678 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001679 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001680 } else {
1681 /* need to double check i->file because we might be doing something
1682 * more complicated by now, like sourcing or substituting. */
1683#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001684 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001685 do {
1686 get_user_input(i);
1687 } while (!*i->p); /* need non-empty line */
1688 i->promptmode = 1; /* PS2 */
1689 i->promptme = 0;
1690 goto take_cached;
1691 }
1692#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001693 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001694 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001695 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001696#if ENABLE_HUSH_INTERACTIVE
1697 if (ch == '\n')
1698 i->promptme = 1;
1699#endif
1700 return ch;
1701}
1702
Denis Vlasenko913a2012009-04-05 22:17:04 +00001703/* All callers guarantee this routine will never
1704 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001705 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001706static int FAST_FUNC file_peek(struct in_str *i)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001707{
1708 int ch;
1709 if (i->p && *i->p) {
1710 if (i->eof_flag && !i->p[1])
1711 return EOF;
1712 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001713 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001714 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001715 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001716 i->eof_flag = (ch == EOF);
1717 i->peek_buf[0] = ch;
1718 i->peek_buf[1] = '\0';
1719 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001720 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001721 return ch;
1722}
1723
1724static void setup_file_in_str(struct in_str *i, FILE *f)
1725{
1726 i->peek = file_peek;
1727 i->get = file_get;
1728#if ENABLE_HUSH_INTERACTIVE
1729 i->promptme = 1;
1730 i->promptmode = 0; /* PS1 */
1731#endif
1732 i->file = f;
1733 i->p = NULL;
1734}
1735
1736static void setup_string_in_str(struct in_str *i, const char *s)
1737{
1738 i->peek = static_peek;
1739 i->get = static_get;
1740#if ENABLE_HUSH_INTERACTIVE
1741 i->promptme = 1;
1742 i->promptmode = 0; /* PS1 */
1743#endif
1744 i->p = s;
1745 i->eof_flag = 0;
1746}
1747
1748
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001749/*
1750 * o_string support
1751 */
1752#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001753
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001754static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001755{
1756 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001757 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001758 if (o->data)
1759 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001760}
1761
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001762static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001763{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001764 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001765 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001766}
1767
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001768static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1769{
1770 free(o->data);
1771}
1772
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001773static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001774{
1775 if (o->length + len > o->maxlen) {
1776 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1777 o->data = xrealloc(o->data, 1 + o->maxlen);
1778 }
1779}
1780
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001781static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001782{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001783 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1784 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001785 o->data[o->length] = ch;
1786 o->length++;
1787 o->data[o->length] = '\0';
1788}
1789
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001790static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001791{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001792 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001793 memcpy(&o->data[o->length], str, len);
1794 o->length += len;
1795 o->data[o->length] = '\0';
1796}
1797
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001798#if !BB_MMU
1799static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001800{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001801 o_addblock(o, str, strlen(str));
1802}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001803static void nommu_addchr(o_string *o, int ch)
1804{
1805 if (o)
1806 o_addchr(o, ch);
1807}
1808#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001809# define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001810#endif
1811
1812static void o_addstr_with_NUL(o_string *o, const char *str)
1813{
1814 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001815}
1816
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001817static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001818{
1819 while (len) {
1820 o_addchr(o, *str);
1821 if (*str++ == '\\'
1822 && (*str != '*' && *str != '?' && *str != '[')
1823 ) {
1824 o_addchr(o, '\\');
1825 }
1826 len--;
1827 }
1828}
1829
Eric Andersen25f27032001-04-26 23:22:31 +00001830/* My analysis of quoting semantics tells me that state information
1831 * is associated with a destination, not a source.
1832 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001833static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001834{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001835 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001836 char *found = strchr("*?[\\", ch);
1837 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001838 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001839 o_grow_by(o, sz);
1840 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001841 o->data[o->length] = '\\';
1842 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001843 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001844 o->data[o->length] = ch;
1845 o->length++;
1846 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001847}
1848
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001849static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001850{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001851 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001852 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001853 sz++;
1854 o->data[o->length] = '\\';
1855 o->length++;
1856 }
1857 o_grow_by(o, sz);
1858 o->data[o->length] = ch;
1859 o->length++;
1860 o->data[o->length] = '\0';
1861}
1862
1863static void o_addQstr(o_string *o, const char *str, int len)
1864{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001865 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001866 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001867 return;
1868 }
1869 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001870 char ch;
1871 int sz;
1872 int ordinary_cnt = strcspn(str, "*?[\\");
1873 if (ordinary_cnt > len) /* paranoia */
1874 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001875 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001876 if (ordinary_cnt == len)
1877 return;
1878 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001879 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001880
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001881 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001882 sz = 1;
1883 if (ch) { /* it is necessarily one of "*?[\\" */
1884 sz++;
1885 o->data[o->length] = '\\';
1886 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001887 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001888 o_grow_by(o, sz);
1889 o->data[o->length] = ch;
1890 o->length++;
1891 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001892 }
1893}
1894
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001895/* A special kind of o_string for $VAR and `cmd` expansion.
1896 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001897 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001898 * list[i] contains an INDEX (int!) into this string data.
1899 * It means that if list[] needs to grow, data needs to be moved higher up
1900 * but list[i]'s need not be modified.
1901 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001902 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001903 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1904 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001905#if DEBUG_EXPAND || DEBUG_GLOB
1906static void debug_print_list(const char *prefix, o_string *o, int n)
1907{
1908 char **list = (char**)o->data;
1909 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1910 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001911
1912 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001913 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1914 prefix, list, n, string_start, o->length, o->maxlen);
1915 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001916 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001917 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1918 o->data + (int)list[i] + string_start,
1919 o->data + (int)list[i] + string_start);
1920 i++;
1921 }
1922 if (n) {
1923 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001924 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001925 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001926 }
1927}
1928#else
Denys Vlasenko28a105d2009-06-01 11:26:30 +02001929# define debug_print_list(prefix, o, n) ((void)0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001930#endif
1931
1932/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1933 * in list[n] so that it points past last stored byte so far.
1934 * It returns n+1. */
1935static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001936{
1937 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001938 int string_start;
1939 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001940
1941 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001942 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1943 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001944 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001945 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001946 /* list[n] points to string_start, make space for 16 more pointers */
1947 o->maxlen += 0x10 * sizeof(list[0]);
1948 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001949 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001950 memmove(list + n + 0x10, list + n, string_len);
1951 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001952 } else {
1953 debug_printf_list("list[%d]=%d string_start=%d\n",
1954 n, string_len, string_start);
1955 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001956 } else {
1957 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001958 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1959 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001960 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1961 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001962 o->has_empty_slot = 0;
1963 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001964 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001965 return n + 1;
1966}
1967
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001968/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001969static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001970{
1971 char **list = (char**)o->data;
1972 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1973
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001974 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001975}
1976
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001977/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001978 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001979static int o_glob(o_string *o, int n)
1980{
1981 glob_t globdata;
1982 int gr;
1983 char *pattern;
1984
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001985 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001986 if (!o->data)
1987 return o_save_ptr_helper(o, n);
1988 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001989 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001990 if (!glob_needed(pattern)) {
1991 literal:
1992 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001993 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001994 return o_save_ptr_helper(o, n);
1995 }
1996
1997 memset(&globdata, 0, sizeof(globdata));
1998 gr = glob(pattern, 0, NULL, &globdata);
1999 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2000 if (gr == GLOB_NOSPACE)
2001 bb_error_msg_and_die("out of memory during glob");
2002 if (gr == GLOB_NOMATCH) {
2003 globfree(&globdata);
2004 goto literal;
2005 }
2006 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002007 /* TODO: testcase for bad glob pattern behavior */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002008 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
2009 }
2010 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2011 char **argv = globdata.gl_pathv;
2012 o->length = pattern - o->data; /* "forget" pattern */
2013 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002014 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002015 n = o_save_ptr_helper(o, n);
2016 argv++;
2017 if (!*argv)
2018 break;
2019 }
2020 }
2021 globfree(&globdata);
2022 if (DEBUG_GLOB)
2023 debug_print_list("o_glob returning", o, n);
2024 return n;
2025}
2026
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002027/* If o->o_glob == 1, glob the string so far remembered.
2028 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002029static int o_save_ptr(o_string *o, int n)
2030{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00002031 if (o->o_glob) { /* if globbing is requested */
2032 /* If o->has_empty_slot, list[n] was already globbed
2033 * (if it was requested back then when it was filled)
2034 * so don't do that again! */
2035 if (!o->has_empty_slot)
2036 return o_glob(o, n); /* o_save_ptr_helper is inside */
2037 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002038 return o_save_ptr_helper(o, n);
2039}
2040
2041/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002042static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002043{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002044 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002045 int string_start;
2046
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002047 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2048 if (DEBUG_EXPAND)
2049 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002050 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002051 list = (char**)o->data;
2052 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2053 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002054 while (n) {
2055 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00002056 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002057 }
2058 return list;
2059}
2060
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002061
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002062/* Expansion can recurse */
2063#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002064static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002065#endif
2066static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002067#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002068#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002069 parse_stream_dquoted(dest, input, dquote_end)
2070#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002071static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002072 o_string *dest,
2073 struct in_str *input,
2074 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002075
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002076/* expand_strvec_to_strvec() takes a list of strings, expands
2077 * all variable references within and returns a pointer to
2078 * a list of expanded strings, possibly with larger number
2079 * of strings. (Think VAR="a b"; echo $VAR).
2080 * This new list is allocated as a single malloc block.
2081 * NULL-terminated list of char* pointers is at the beginning of it,
2082 * followed by strings themself.
2083 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00002084
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002085/* Store given string, finalizing the word and starting new one whenever
2086 * we encounter IFS char(s). This is used for expanding variable values.
2087 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2088static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002089{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002090 while (1) {
2091 int word_len = strcspn(str, G.ifs);
2092 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002093 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002094 o_addQstr(output, str, word_len);
2095 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002096 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097 str += word_len;
2098 }
2099 if (!*str) /* EOL - do not finalize word */
2100 break;
2101 o_addchr(output, '\0');
2102 debug_print_list("expand_on_ifs", output, n);
2103 n = o_save_ptr(output, n);
2104 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002105 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002106 debug_print_list("expand_on_ifs[1]", output, n);
2107 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002108}
2109
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002110/* Helper to expand $((...)) and heredoc body. These act as if
2111 * they are in double quotes, with the exception that they are not :).
2112 * Just the rules are similar: "expand only $var and `cmd`"
2113 *
2114 * Returns malloced string.
2115 * As an optimization, we return NULL if expansion is not needed.
2116 */
2117static char *expand_pseudo_dquoted(const char *str)
2118{
2119 char *exp_str;
2120 struct in_str input;
2121 o_string dest = NULL_O_STRING;
2122
2123 if (strchr(str, '$') == NULL
2124#if ENABLE_HUSH_TICK
2125 && strchr(str, '`') == NULL
2126#endif
2127 ) {
2128 return NULL;
2129 }
2130
2131 /* We need to expand. Example:
2132 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2133 */
2134 setup_string_in_str(&input, str);
2135 parse_stream_dquoted(NULL, &dest, &input, EOF);
2136 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2137 exp_str = expand_string_to_string(dest.data);
2138 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2139 o_free_unsafe(&dest);
2140 return exp_str;
2141}
2142
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002143/* Expand all variable references in given string, adding words to list[]
2144 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2145 * to be filled). This routine is extremely tricky: has to deal with
2146 * variables/parameters with whitespace, $* and $@, and constructs like
2147 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2148static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002149{
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002150 /* or_mask is either 0 (normal case) or 0x80 -
2151 * expansion of right-hand side of assignment == 1-element expand.
2152 * It will also do no globbing, and thus we must not backslash-quote!
2153 */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002154 char ored_ch;
2155 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002156
2157 ored_ch = 0;
2158
2159 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2160 debug_print_list("expand_vars_to_list", output, n);
2161 n = o_save_ptr(output, n);
2162 debug_print_list("expand_vars_to_list[0]", output, n);
2163
2164 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002165 char first_ch;
2166 int i;
2167 char *dyn_val = NULL;
2168 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002169#if ENABLE_HUSH_TICK
2170 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002171#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002172#if ENABLE_SH_MATH_SUPPORT
2173 char arith_buf[sizeof(arith_t)*3 + 2];
2174#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002175 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002176 debug_print_list("expand_vars_to_list[1]", output, n);
2177 arg = ++p;
2178 p = strchr(p, SPECIAL_VAR_SYMBOL);
2179
2180 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2181 /* "$@" is special. Even if quoted, it can still
2182 * expand to nothing (not even an empty string) */
2183 if ((first_ch & 0x7f) != '@')
2184 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002185
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002186 switch (first_ch & 0x7f) {
2187 /* Highest bit in first_ch indicates that var is double-quoted */
2188 case '$': /* pid */
2189 val = utoa(G.root_pid);
2190 break;
2191 case '!': /* bg pid */
2192 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2193 break;
2194 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002195 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002196 break;
2197 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002198 if (arg[1] != SPECIAL_VAR_SYMBOL)
2199 /* actually, it's a ${#var} */
2200 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002201 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2202 break;
2203 case '*':
2204 case '@':
2205 i = 1;
2206 if (!G.global_argv[i])
2207 break;
2208 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2209 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002210 smallint sv = output->o_escape;
2211 /* unquoted var's contents should be globbed, so don't escape */
2212 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 while (G.global_argv[i]) {
2214 n = expand_on_ifs(output, n, G.global_argv[i]);
2215 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2216 if (G.global_argv[i++][0] && G.global_argv[i]) {
2217 /* this argv[] is not empty and not last:
2218 * put terminating NUL, start new word */
2219 o_addchr(output, '\0');
2220 debug_print_list("expand_vars_to_list[2]", output, n);
2221 n = o_save_ptr(output, n);
2222 debug_print_list("expand_vars_to_list[3]", output, n);
2223 }
2224 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002225 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002226 } else
2227 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2228 * and in this case should treat it like '$*' - see 'else...' below */
2229 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2230 while (1) {
2231 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2232 if (++i >= G.global_argc)
2233 break;
2234 o_addchr(output, '\0');
2235 debug_print_list("expand_vars_to_list[4]", output, n);
2236 n = o_save_ptr(output, n);
2237 }
2238 } else { /* quoted $*: add as one word */
2239 while (1) {
2240 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2241 if (!G.global_argv[++i])
2242 break;
2243 if (G.ifs[0])
2244 o_addchr(output, G.ifs[0]);
2245 }
2246 }
2247 break;
2248 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2249 /* "Empty variable", used to make "" etc to not disappear */
2250 arg++;
2251 ored_ch = 0x80;
2252 break;
2253#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002254 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002255 *p = '\0';
2256 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002257 /* Can't just stuff it into output o_string,
2258 * expanded result may need to be globbed
2259 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002260 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002261 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002262 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2263 val = subst_result.data;
2264 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002265#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002266#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002267 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002268 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002269 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002270 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002271 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002272
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002273 arg++; /* skip '+' */
2274 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002275 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002276
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002277 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002278 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002279 hooks.setvar = arith_set_local_var;
2280 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002281 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2282 free(exp_str);
2283
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002284 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002285 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002286 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002287 case -3:
2288 msg = "exponent less than 0";
2289 break;
2290 case -2:
2291 msg = "divide by 0";
2292 break;
2293 case -5:
2294 msg = "expression recursion loop detected";
2295 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002296 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002297 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002298 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002299 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002300 sprintf(arith_buf, arith_t_fmt, res);
2301 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002302 break;
2303 }
2304#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002305 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002306 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002307 bool exp_len = false;
2308 bool exp_null = false;
2309 char *var = arg;
2310 char exp_save = exp_save; /* for compiler */
2311 char exp_op = exp_op; /* for compiler */
2312 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002313 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002314
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 *p = '\0';
2316 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002317
2318 /* prepare for expansions */
2319 if (var[0] == '#') {
2320 /* handle length expansion ${#var} */
2321 exp_len = true;
2322 ++var;
2323 } else {
2324 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002325 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002326 if (!var[exp_off])
2327 exp_off = 0;
2328 if (exp_off) {
2329 exp_save = var[exp_off];
2330 exp_null = exp_save == ':';
2331 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002332 if (exp_null)
2333 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002334 exp_op = *exp_word++;
2335 var[exp_off] = '\0';
2336 }
2337 }
2338
2339 /* lookup the variable in question */
2340 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002341 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002342 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002343 if (i < G.global_argc)
2344 val = G.global_argv[i];
2345 /* else val remains NULL: $N with too big N */
2346 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002347 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002348
2349 /* handle any expansions */
2350 if (exp_len) {
2351 debug_printf_expand("expand: length of '%s' = ", val);
2352 val = utoa(val ? strlen(val) : 0);
2353 debug_printf_expand("%s\n", val);
2354 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002355 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002356 if (val) {
2357 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002358 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002359 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002360 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002361 if (exp_op == *exp_word) /* ## or %% */
2362 ++exp_word;
2363 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002364 loc = scan(dyn_val, exp_word, match_at_left);
2365 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002366 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002367 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002368 *loc = '\0';
2369 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002370 } else {
2371 /* we need to do an expansion */
2372 int exp_test = (!val || (exp_null && !val[0]));
2373 if (exp_op == '+')
2374 exp_test = !exp_test;
2375 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2376 exp_null ? "true" : "false", exp_test);
2377 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002378 if (exp_op == '?') {
2379//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002380 /* ${var?[error_msg_if_unset]} */
2381 /* ${var:?[error_msg_if_unset_or_null]} */
2382 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002383 die_if_script("%s: %s",
2384 var,
2385 exp_word[0] ? exp_word : "parameter null or not set"
2386 );
2387 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002388 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002389 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002390
Mike Frysingera4f331d2009-04-07 06:03:22 +00002391 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002392 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002393 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002394 /* mimic bash message */
2395 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002396 val = NULL;
2397 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002398 char *new_var = xasprintf("%s=%s", var, val);
Denys Vlasenko295fef82009-06-03 12:47:26 +02002399 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002400 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002401 }
2402 }
2403 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002404
Mike Frysinger6379bb42009-03-28 18:55:03 +00002405 var[exp_off] = exp_save;
2406 }
2407
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002408 arg[0] = first_ch;
2409#if ENABLE_HUSH_TICK
2410 store_val:
2411#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002412 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002413 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002414 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002415 /* unquoted var's contents should be globbed, so don't escape */
2416 smallint sv = output->o_escape;
2417 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002418 n = expand_on_ifs(output, n, val);
2419 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002420 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002421 }
2422 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002423 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002424 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002425 } /* default: */
2426 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002427
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002428 if (val) {
2429 o_addQstr(output, val, strlen(val));
2430 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002431 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002432 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002433 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002434 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002435
2436#if ENABLE_HUSH_TICK
2437 o_free(&subst_result);
2438#endif
2439 arg = ++p;
2440 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2441
2442 if (arg[0]) {
2443 debug_print_list("expand_vars_to_list[a]", output, n);
2444 /* this part is literal, and it was already pre-quoted
2445 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002446 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002447 debug_print_list("expand_vars_to_list[b]", output, n);
2448 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2449 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2450 ) {
2451 n--;
2452 /* allow to reuse list[n] later without re-growth */
2453 output->has_empty_slot = 1;
2454 } else {
2455 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002456 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002457 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002458}
2459
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002460static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002461{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002462 int n;
2463 char **list;
2464 char **v;
2465 o_string output = NULL_O_STRING;
2466
2467 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002468 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002469 /* (unquoted $var will temporarily switch it off) */
2470 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002471 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002472
2473 n = 0;
2474 v = argv;
2475 while (*v) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002476 n = expand_vars_to_list(&output, n, *v, (unsigned char)or_mask);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002477 v++;
2478 }
2479 debug_print_list("expand_variables", &output, n);
2480
2481 /* output.data (malloced in one block) gets returned in "list" */
2482 list = o_finalize_list(&output, n);
2483 debug_print_strings("expand_variables[1]", list);
2484 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002485}
2486
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002487static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002488{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002489 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002490}
2491
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002492#if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002493static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
2494{
2495 return expand_variables(argv, 0x80);
2496}
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02002497#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002498
2499#ifdef CMD_SINGLEWORD_NOGLOB_COND
2500static char **expand_strvec_to_strvec_singleword_noglob_cond(char **argv)
2501{
2502 int n;
2503 char **list;
2504 char **v;
2505 o_string output = NULL_O_STRING;
2506
2507 n = 0;
2508 v = argv;
2509 while (*v) {
2510 int is_var = is_well_formed_var_name(*v, '=');
2511 /* is_var * 0x80: singleword expansion for vars */
2512 n = expand_vars_to_list(&output, n, *v, is_var * 0x80);
2513
2514 /* Subtle! expand_vars_to_list did not glob last word yet.
2515 * It does this only when fed with further data.
2516 * Therefore we set globbing flags AFTER it, not before:
2517 */
2518
2519 /* if it is not recognizably abc=...; then: */
2520 output.o_escape = !is_var; /* protect against globbing for "$var" */
2521 /* (unquoted $var will temporarily switch it off) */
2522 output.o_glob = !is_var; /* and indeed do globbing */
2523 v++;
2524 }
2525 debug_print_list("expand_cond", &output, n);
2526
2527 /* output.data (malloced in one block) gets returned in "list" */
2528 list = o_finalize_list(&output, n);
2529 debug_print_strings("expand_cond[1]", list);
2530 return list;
2531}
2532#endif
2533
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002534/* Used for expansion of right hand of assignments */
2535/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2536 * "v=/bin/c*" */
2537static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002538{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002539 char *argv[2], **list;
2540
2541 argv[0] = (char*)str;
2542 argv[1] = NULL;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002543 list = expand_variables(argv, 0x80); /* 0x80: singleword expansion */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002544 if (HUSH_DEBUG)
2545 if (!list[0] || list[1])
2546 bb_error_msg_and_die("BUG in varexp2");
2547 /* actually, just move string 2*sizeof(char*) bytes back */
2548 overlapping_strcpy((char*)list, list[0]);
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02002549 unbackslash((char*)list);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2551 return (char*)list;
2552}
2553
2554/* Used for "eval" builtin */
2555static char* expand_strvec_to_string(char **argv)
2556{
2557 char **list;
2558
2559 list = expand_variables(argv, 0x80);
2560 /* Convert all NULs to spaces */
2561 if (list[0]) {
2562 int n = 1;
2563 while (list[n]) {
2564 if (HUSH_DEBUG)
2565 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2566 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002567 /* bash uses ' ' regardless of $IFS contents */
2568 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002569 n++;
2570 }
2571 }
2572 overlapping_strcpy((char*)list, list[0]);
2573 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2574 return (char*)list;
2575}
2576
2577static char **expand_assignments(char **argv, int count)
2578{
2579 int i;
2580 char **p = NULL;
2581 /* Expand assignments into one string each */
2582 for (i = 0; i < count; i++) {
2583 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2584 }
2585 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002586}
2587
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002588
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002589#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002590/* never called */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002591void re_execute_shell(char ***to_free, const char *s,
2592 char *g_argv0, char **g_argv,
2593 char **builtin_argv) NORETURN;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002594
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002595static void reset_traps_to_defaults(void)
2596{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002597 /* This function is always called in a child shell
2598 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002599 * Child shells are not interactive.
2600 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2601 * Testcase: (while :; do :; done) + ^Z should background.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002602 * Same goes for SIGTERM, SIGHUP, SIGINT.
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002603 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002604 unsigned sig;
2605 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002606
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002607 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2608 return;
2609
2610 /* Stupid. It can be done with *single* &= op, but we can't use
2611 * the fact that G.blocked_set is implemented as a bitmask... */
2612 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2613 sig = 1;
2614 while (1) {
2615 if (mask & 1)
2616 sigdelset(&G.blocked_set, sig);
2617 mask >>= 1;
2618 if (!mask)
2619 break;
2620 sig++;
2621 }
2622
2623 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2624 mask = G.non_DFL_mask;
2625 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2626 if (!G.traps[sig])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002627 continue;
2628 free(G.traps[sig]);
2629 G.traps[sig] = NULL;
2630 /* There is no signal for 0 (EXIT) */
2631 if (sig == 0)
2632 continue;
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002633 /* There was a trap handler, we are removing it.
2634 * But if sig still has non-DFL handling,
2635 * we should not unblock it. */
2636 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002637 continue;
2638 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002639 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002640 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002641}
2642
2643#else /* !BB_MMU */
2644
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002645static void re_execute_shell(char ***to_free, const char *s,
2646 char *g_argv0, char **g_argv,
2647 char **builtin_argv) NORETURN;
2648static void re_execute_shell(char ***to_free, const char *s,
2649 char *g_argv0, char **g_argv,
2650 char **builtin_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002651{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002652 char param_buf[sizeof("-$%x:%x:%x:%x:%x") + sizeof(unsigned) * 2];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002653 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002654 struct variable *cur;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002655#if ENABLE_HUSH_FUNCTIONS
2656 struct function *funcp;
2657#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002658 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002659 unsigned cnt;
2660
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002661 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002662 argv = heredoc_argv;
2663 argv[0] = (char *) G.argv0_for_re_execing;
2664 argv[1] = (char *) "-<";
2665 argv[2] = (char *) s;
2666 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002667 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002668 goto do_exec;
2669 }
2670
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002671 cnt = 0;
2672 pp = builtin_argv;
2673 if (pp) while (*pp++)
2674 cnt++;
2675
2676 sprintf(param_buf, "-$%x:%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002677 , (unsigned) G.root_pid
2678 , (unsigned) G.last_bg_pid
2679 , (unsigned) G.last_exitcode
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002680 , cnt
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002681 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002682 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002683 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002684 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002685 */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002686 cnt += 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002687 for (cur = G.top_var; cur; cur = cur->next) {
2688 if (!cur->flg_export || cur->flg_read_only)
2689 cnt += 2;
2690 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002691#if ENABLE_HUSH_FUNCTIONS
2692 for (funcp = G.top_func; funcp; funcp = funcp->next)
2693 cnt += 3;
2694#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002695 pp = g_argv;
2696 while (*pp++)
2697 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002698 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002699 *pp++ = (char *) G.argv0_for_re_execing;
2700 *pp++ = param_buf;
2701 for (cur = G.top_var; cur; cur = cur->next) {
2702 if (cur->varstr == hush_version_str)
2703 continue;
2704 if (cur->flg_read_only) {
2705 *pp++ = (char *) "-R";
2706 *pp++ = cur->varstr;
2707 } else if (!cur->flg_export) {
2708 *pp++ = (char *) "-V";
2709 *pp++ = cur->varstr;
2710 }
2711 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002712#if ENABLE_HUSH_FUNCTIONS
2713 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2714 *pp++ = (char *) "-F";
2715 *pp++ = funcp->name;
2716 *pp++ = funcp->body_as_string;
2717 }
2718#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002719 /* We can pass activated traps here. Say, -Tnn:trap_string
2720 *
2721 * However, POSIX says that subshells reset signals with traps
2722 * to SIG_DFL.
2723 * I tested bash-3.2 and it not only does that with true subshells
2724 * of the form ( list ), but with any forked children shells.
2725 * I set trap "echo W" WINCH; and then tried:
2726 *
2727 * { echo 1; sleep 20; echo 2; } &
2728 * while true; do echo 1; sleep 20; echo 2; break; done &
2729 * true | { echo 1; sleep 20; echo 2; } | cat
2730 *
2731 * In all these cases sending SIGWINCH to the child shell
2732 * did not run the trap. If I add trap "echo V" WINCH;
2733 * _inside_ group (just before echo 1), it works.
2734 *
2735 * I conclude it means we don't need to pass active traps here.
2736 * exec syscall below resets them to SIG_DFL for us.
2737 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002738 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002739 *pp++ = (char *) s;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002740 if (builtin_argv) {
2741 while (*++builtin_argv)
2742 *pp++ = *builtin_argv;
2743 *pp++ = (char *) "";
2744 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002745 *pp++ = g_argv0;
2746 while (*g_argv)
2747 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002748 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002749 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002750
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002751 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002752 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2753 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002754 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002755 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002756 if (argv[0][0] == '/')
2757 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002758 xfunc_error_retval = 127;
2759 bb_error_msg_and_die("can't re-execute the shell");
2760}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002761#endif /* !BB_MMU */
2762
2763
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002764static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002765{
2766 struct fd_pair pair;
2767 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002768 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002769 /* the _body_ of heredoc (misleading field name) */
2770 const char *heredoc = redir->rd_filename;
2771 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002772#if !BB_MMU
2773 char **to_free;
2774#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002775
2776 expanded = NULL;
2777 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2778 expanded = expand_pseudo_dquoted(heredoc);
2779 if (expanded)
2780 heredoc = expanded;
2781 }
2782 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002783
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002784 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002785 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002786 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002787
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002788 /* Try writing without forking. Newer kernels have
2789 * dynamically growing pipes. Must use non-blocking write! */
2790 ndelay_on(pair.wr);
2791 while (1) {
2792 written = write(pair.wr, heredoc, len);
2793 if (written <= 0)
2794 break;
2795 len -= written;
2796 if (len == 0) {
2797 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002798 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002799 return;
2800 }
2801 heredoc += written;
2802 }
2803 ndelay_off(pair.wr);
2804
2805 /* Okay, pipe buffer was not big enough */
2806 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002807 * for the unsuspecting parent process. Child creates a grandchild
2808 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002809 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002810#if !BB_MMU
2811 to_free = NULL;
2812#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002813 pid = vfork();
2814 if (pid < 0)
2815 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002816 if (pid == 0) {
2817 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002818 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002819 pid = BB_MMU ? fork() : vfork();
2820 if (pid < 0)
2821 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2822 if (pid != 0)
2823 _exit(0);
2824 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002825 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002826#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002827 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002828 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002829#else
2830 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002831 xmove_fd(pair.wr, STDOUT_FILENO);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02002832 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002833#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002834 }
2835 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02002836#if ENABLE_HUSH_FAST
2837 G.count_SIGCHLD++;
2838//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2839#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002840 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002841#if !BB_MMU
2842 free(to_free);
2843#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002844 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002845 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002846 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002847}
2848
Eric Andersen25f27032001-04-26 23:22:31 +00002849/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2850 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002851static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002852{
2853 int openfd, mode;
2854 struct redir_struct *redir;
2855
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002856 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002857 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002858 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002859 if (squirrel && redir->rd_fd < 3
2860 && squirrel[redir->rd_fd] < 0
2861 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002862 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002863 }
2864 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2865 * of the heredoc */
2866 debug_printf_parse("set heredoc '%s'\n",
2867 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002868 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002869 continue;
2870 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002871
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002872 if (redir->rd_dup == REDIRFD_TO_FILE) {
2873 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002874 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002875 if (redir->rd_filename == NULL) {
2876 /* Something went wrong in the parse.
2877 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002878 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002879 continue;
2880 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002881 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002882 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002883 openfd = open_or_warn(p, mode);
2884 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002885 if (openfd < 0) {
2886 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002887 * bash and ash both lose it as well (though zsh doesn't!) */
2888//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002889 return 1;
2890 }
2891 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002892 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002893 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002894 }
2895
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002896 if (openfd != redir->rd_fd) {
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);
Eric Andersen25f27032001-04-26 23:22:31 +00002901 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002902 if (openfd == REDIRFD_CLOSE) {
2903 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002904 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002905 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002906 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002907 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002908 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002909 }
Eric Andersen25f27032001-04-26 23:22:31 +00002910 }
2911 }
2912 return 0;
2913}
2914
2915static void restore_redirects(int squirrel[])
2916{
2917 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002918 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002919 fd = squirrel[i];
2920 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002921 /* We simply die on error */
2922 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002923 }
2924 }
2925}
2926
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002927
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002928static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002929
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002930/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002931static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002932{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002933 char **p;
2934 struct command *command;
2935 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002936 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002937
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002938 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002939 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002940 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002941 for (i = 0; i < pi->num_cmds; i++) {
2942 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002943 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002944 if (command->argv) {
2945 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002946 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002947 }
2948 free_strings(command->argv);
2949 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002950 }
2951 /* not "else if": on syntax error, we may have both! */
2952 if (command->group) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02002953 debug_printf_clean(" begin group (cmd_type:%d)\n",
2954 command->cmd_type);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002955 free_pipe_list(command->group);
2956 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002957 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002958 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002959 /* else is crucial here.
2960 * If group != NULL, child_func is meaningless */
2961#if ENABLE_HUSH_FUNCTIONS
2962 else if (command->child_func) {
2963 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2964 command->child_func->parent_cmd = NULL;
2965 }
2966#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002967#if !BB_MMU
2968 free(command->group_as_string);
2969 command->group_as_string = NULL;
2970#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002971 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002972 debug_printf_clean(" redirect %d%s",
2973 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002974 /* guard against the case >$FOO, where foo is unset or blank */
2975 if (r->rd_filename) {
2976 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2977 free(r->rd_filename);
2978 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002979 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002980 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002981 rnext = r->next;
2982 free(r);
2983 }
2984 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002985 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002986 free(pi->cmds); /* children are an array, they get freed all at once */
2987 pi->cmds = NULL;
2988#if ENABLE_HUSH_JOB
2989 free(pi->cmdtext);
2990 pi->cmdtext = NULL;
2991#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002992}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002993
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002994static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002995{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996 struct pipe *pi, *next;
2997
2998 for (pi = head; pi; pi = next) {
2999#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003000 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003001#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003002 free_pipe(pi);
3003 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003004 next = pi->next;
3005 /*pi->next = NULL;*/
3006 free(pi);
3007 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003008}
3009
3010
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003011static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003012#if BB_MMU
3013#define parse_stream(pstring, input, end_trigger) \
3014 parse_stream(input, end_trigger)
3015#endif
3016static struct pipe *parse_stream(char **pstring,
3017 struct in_str *input,
3018 int end_trigger);
3019static void parse_and_run_string(const char *s);
3020
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003021
Mike Frysinger93cadc22009-05-27 17:06:25 -04003022static char *find_in_path(const char *arg)
3023{
3024 char *ret = NULL;
3025 const char *PATH = get_local_var_value("PATH");
3026
3027 if (!PATH)
3028 return NULL;
3029
3030 while (1) {
3031 const char *end = strchrnul(PATH, ':');
3032 int sz = end - PATH; /* must be int! */
3033
3034 free(ret);
3035 if (sz != 0) {
3036 ret = xasprintf("%.*s/%s", sz, PATH, arg);
3037 } else {
3038 /* We have xxx::yyyy in $PATH,
3039 * it means "use current dir" */
3040 ret = xstrdup(arg);
3041 }
3042 if (access(ret, F_OK) == 0)
3043 break;
3044
3045 if (*end == '\0') {
3046 free(ret);
3047 return NULL;
3048 }
3049 PATH = end + 1;
3050 }
3051
3052 return ret;
3053}
3054
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003055static const struct built_in_command* find_builtin_helper(const char *name,
3056 const struct built_in_command *x,
3057 const struct built_in_command *end)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003058{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003059 while (x != end) {
3060 if (strcmp(name, x->cmd) != 0) {
3061 x++;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003062 continue;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003063 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003064 debug_printf_exec("found builtin '%s'\n", name);
3065 return x;
3066 }
3067 return NULL;
3068}
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003069static const struct built_in_command* find_builtin1(const char *name)
3070{
3071 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
3072}
3073static const struct built_in_command* find_builtin(const char *name)
3074{
3075 const struct built_in_command *x = find_builtin1(name);
3076 if (x)
3077 return x;
3078 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
3079}
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003080
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003081#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko873273d2009-09-12 14:47:41 +02003082static struct function **find_function_slot(const char *name)
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003083{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003084 struct function **funcpp = &G.top_func;
3085 while (*funcpp) {
3086 if (strcmp(name, (*funcpp)->name) == 0) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003087 break;
3088 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003089 funcpp = &(*funcpp)->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003090 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003091 return funcpp;
3092}
3093
3094static const struct function *find_function(const char *name)
3095{
3096 const struct function *funcp = *find_function_slot(name);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003097 if (funcp)
3098 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003099 return funcp;
3100}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003101
Denis Vlasenkobc569742009-04-12 20:35:19 +00003102/* Note: takes ownership on name ptr */
3103static struct function *new_function(char *name)
3104{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003105 struct function **funcpp = find_function_slot(name);
3106 struct function *funcp = *funcpp;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003107
Denys Vlasenko873273d2009-09-12 14:47:41 +02003108 if (funcp != NULL) {
3109 struct command *cmd = funcp->parent_cmd;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003110 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
3111 if (!cmd) {
3112 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
3113 free(funcp->name);
3114 /* Note: if !funcp->body, do not free body_as_string!
3115 * This is a special case of "-F name body" function:
3116 * body_as_string was not malloced! */
3117 if (funcp->body) {
3118 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003119# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003120 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003121# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003122 }
3123 } else {
3124 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
3125 cmd->argv[0] = funcp->name;
3126 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003127# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003128 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003129# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003130 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003131 } else {
3132 debug_printf_exec("remembering new function '%s'\n", name);
3133 funcp = *funcpp = xzalloc(sizeof(*funcp));
3134 /*funcp->next = NULL;*/
Denis Vlasenkobc569742009-04-12 20:35:19 +00003135 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003136
Denis Vlasenkobc569742009-04-12 20:35:19 +00003137 funcp->name = name;
3138 return funcp;
3139}
3140
Denis Vlasenko40e84372009-04-18 11:23:38 +00003141static void unset_func(const char *name)
3142{
Denys Vlasenko873273d2009-09-12 14:47:41 +02003143 struct function **funcpp = find_function_slot(name);
3144 struct function *funcp = *funcpp;
Denis Vlasenko40e84372009-04-18 11:23:38 +00003145
Denys Vlasenko873273d2009-09-12 14:47:41 +02003146 if (funcp != NULL) {
3147 debug_printf_exec("freeing function '%s'\n", funcp->name);
3148 *funcpp = funcp->next;
3149 /* funcp is unlinked now, deleting it.
3150 * Note: if !funcp->body, the function was created by
3151 * "-F name body", do not free ->body_as_string
3152 * and ->name as they were not malloced. */
3153 if (funcp->body) {
3154 free_pipe_list(funcp->body);
3155 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003156# if !BB_MMU
Denys Vlasenko873273d2009-09-12 14:47:41 +02003157 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003158# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00003159 }
Denys Vlasenko873273d2009-09-12 14:47:41 +02003160 free(funcp);
Denis Vlasenko40e84372009-04-18 11:23:38 +00003161 }
3162}
3163
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003164# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003165#define exec_function(to_free, funcp, argv) \
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003166 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003167# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003168static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003169 const struct function *funcp,
3170 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003171static void exec_function(char ***to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003172 const struct function *funcp,
3173 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003174{
3175# if BB_MMU
3176 int n = 1;
3177
3178 argv[0] = G.global_argv[0];
3179 G.global_argv = argv;
3180 while (*++argv)
3181 n++;
3182 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003183 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003184 n = run_list(funcp->body);
3185 fflush(NULL);
3186 _exit(n);
3187# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003188 re_execute_shell(to_free,
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003189 funcp->body_as_string,
3190 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003191 argv + 1,
3192 NULL);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003193# endif
3194}
3195
3196static int run_function(const struct function *funcp, char **argv)
3197{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003198 int rc;
3199 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003200 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003201
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003202 save_and_replace_G_args(&sv, argv);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003203
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003204 /* "we are in function, ok to use return" */
3205 sv_flg = G.flag_return_in_progress;
3206 G.flag_return_in_progress = -1;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003207#if ENABLE_HUSH_LOCAL
3208 G.func_nest_level++;
3209#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003210
Denis Vlasenkobc569742009-04-12 20:35:19 +00003211 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003212# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003213 if (!funcp->body) {
3214 /* Function defined by -F */
3215 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003216 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003217 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003218# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003219 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003220 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003221 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003222
Denys Vlasenko295fef82009-06-03 12:47:26 +02003223#if ENABLE_HUSH_LOCAL
3224 {
3225 struct variable *var;
3226 struct variable **var_pp;
3227
3228 var_pp = &G.top_var;
3229 while ((var = *var_pp) != NULL) {
3230 if (var->func_nest_level < G.func_nest_level) {
3231 var_pp = &var->next;
3232 continue;
3233 }
3234 /* Unexport */
3235 if (var->flg_export)
3236 bb_unsetenv(var->varstr);
3237 /* Remove from global list */
3238 *var_pp = var->next;
3239 /* Free */
3240 if (!var->max_len)
3241 free(var->varstr);
3242 free(var);
3243 }
3244 G.func_nest_level--;
3245 }
3246#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003247 G.flag_return_in_progress = sv_flg;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003248
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003249 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003250
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003251 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003252}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003253#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003254
3255
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003256# if BB_MMU
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003257#define exec_builtin(to_free, x, argv) \
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003258 exec_builtin(x, argv)
3259# else
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003260#define exec_builtin(to_free, x, argv) \
3261 exec_builtin(to_free, argv)
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003262# endif
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003263static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003264 const struct built_in_command *x,
3265 char **argv) NORETURN;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003266static void exec_builtin(char ***to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003267 const struct built_in_command *x,
3268 char **argv)
3269{
3270# if BB_MMU
3271 int rcode = x->function(argv);
3272 fflush(NULL);
3273 _exit(rcode);
3274# else
3275 /* On NOMMU, we must never block!
3276 * Example: { sleep 99 | read line; } & echo Ok
3277 */
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003278 re_execute_shell(to_free,
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003279 argv[0],
3280 G.global_argv[0],
3281 G.global_argv + 1,
3282 argv);
3283# endif
3284}
3285
3286
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003287#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003288#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3289 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3290#define pseudo_exec(nommu_save, command, argv_expanded) \
3291 pseudo_exec(command, argv_expanded)
3292#endif
3293
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003294/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003295 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003296 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003297 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003298 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003299static void pseudo_exec_argv(nommu_save_t *nommu_save,
3300 char **argv, int assignment_cnt,
3301 char **argv_expanded) NORETURN;
3302static void pseudo_exec_argv(nommu_save_t *nommu_save,
3303 char **argv, int assignment_cnt,
3304 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003305{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003306 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003307
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003308 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003309 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003310 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003311
Denis Vlasenko9504e442008-10-29 01:19:15 +00003312 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003313#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003314 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003315 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003316 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003317 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003318#else
3319 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003320 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003321#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003322 if (argv_expanded) {
3323 argv = argv_expanded;
3324 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003325 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003326#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003327 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003328#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003329 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003330
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003331#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3332 if (strchr(argv[0], '/') != NULL)
3333 goto skip;
3334#endif
3335
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003336 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003337 * Depending on context, this might be redundant. But it's
3338 * easier to waste a few CPU cycles than it is to figure out
3339 * if this is one of those cases.
3340 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003341 {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003342 /* On NOMMU, it is more expensive to re-execute shell
3343 * just in order to run echo or test builtin.
3344 * It's better to skip it here and run corresponding
3345 * non-builtin later. */
3346 const struct built_in_command *x;
3347 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003348 if (x) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003349 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
Eric Andersen94ac2442001-05-22 19:05:18 +00003350 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003351 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003352#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003353 /* Check if the command matches any functions */
3354 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003355 const struct function *funcp = find_function(argv[0]);
3356 if (funcp) {
Denys Vlasenko764b2f02009-06-07 16:05:04 +02003357 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003358 }
3359 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003360#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003361
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003362#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003363 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003364 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003365 int a = find_applet_by_name(argv[0]);
3366 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003367# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003368 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003369 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003370 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003371 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003372# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003373 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003374 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003375 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3376 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003377 /* If they called chroot or otherwise made the binary no longer
3378 * executable, fall through */
3379 }
3380 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003381#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003382
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003383#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003384 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003385#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003386 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003387 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003388 execvp(argv[0], argv);
Denis Vlasenkof9d4fc32009-04-21 20:40:51 +00003389 bb_perror_msg("can't execute '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00003390 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003391}
3392
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003393/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003394 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003395static void pseudo_exec(nommu_save_t *nommu_save,
3396 struct command *command,
3397 char **argv_expanded) NORETURN;
3398static void pseudo_exec(nommu_save_t *nommu_save,
3399 struct command *command,
3400 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003401{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003402 if (command->argv) {
3403 pseudo_exec_argv(nommu_save, command->argv,
3404 command->assignment_cnt, argv_expanded);
3405 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003406
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003407 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003408 /* Cases when we are here:
3409 * ( list )
3410 * { list } &
3411 * ... | ( list ) | ...
3412 * ... | { list } | ...
3413 */
3414#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003415 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003416 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003417 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003418 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003419 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003420 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003421 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003422#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003423 re_execute_shell(&nommu_save->argv_from_re_execing,
3424 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003425 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02003426 G.global_argv + 1,
3427 NULL);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003428#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003429 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003430
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003431 /* Case when we are here: ... | >file */
3432 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003433 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003434}
3435
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003436#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003437static const char *get_cmdtext(struct pipe *pi)
3438{
3439 char **argv;
3440 char *p;
3441 int len;
3442
3443 /* This is subtle. ->cmdtext is created only on first backgrounding.
3444 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003445 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003446 if (pi->cmdtext)
3447 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003448 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003449 if (!argv || !argv[0]) {
3450 pi->cmdtext = xzalloc(1);
3451 return pi->cmdtext;
3452 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003453
3454 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003455 do {
3456 len += strlen(*argv) + 1;
3457 } while (*++argv);
3458 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003459 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003460 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003461 do {
3462 len = strlen(*argv);
3463 memcpy(p, *argv, len);
3464 p += len;
3465 *p++ = ' ';
3466 } while (*++argv);
3467 p[-1] = '\0';
3468 return pi->cmdtext;
3469}
3470
Eric Andersenbafd94f2001-05-02 16:11:59 +00003471static void insert_bg_job(struct pipe *pi)
3472{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003473 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003474 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003475
3476 /* Linear search for the ID of the job to use */
3477 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003478 for (job = G.job_list; job; job = job->next)
3479 if (job->jobid >= pi->jobid)
3480 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003481
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003482 /* Add job to the list of running jobs */
3483 jobp = &G.job_list;
3484 while ((job = *jobp) != NULL)
3485 jobp = &job->next;
3486 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003487
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003488 *job = *pi; /* physical copy */
3489 job->next = NULL;
3490 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3491 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003492 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003493 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003494 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003495 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003496 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003497
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003498 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003499 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3500 /* Last command's pid goes to $! */
3501 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3502 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003503}
3504
Eric Andersenbafd94f2001-05-02 16:11:59 +00003505static void remove_bg_job(struct pipe *pi)
3506{
3507 struct pipe *prev_pipe;
3508
Denis Vlasenko87a86552008-07-29 19:43:10 +00003509 if (pi == G.job_list) {
3510 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003511 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003512 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003513 while (prev_pipe->next != pi)
3514 prev_pipe = prev_pipe->next;
3515 prev_pipe->next = pi->next;
3516 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003517 if (G.job_list)
3518 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003519 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003520 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003521}
Eric Andersen028b65b2001-06-28 01:10:11 +00003522
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003523/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003524static void delete_finished_bg_job(struct pipe *pi)
3525{
3526 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003527 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003528 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003529 free(pi);
3530}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003531#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003532
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003533/* Check to see if any processes have exited -- if they
3534 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003535static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003536{
Eric Andersenc798b072001-06-22 06:23:03 +00003537 int attributes;
3538 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003539#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003540 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003541#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003542 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003543 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003544
Denis Vlasenkod5762932009-03-31 11:22:57 +00003545 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3546
Eric Andersenc798b072001-06-22 06:23:03 +00003547 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003548 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003549 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003550
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003551 errno = 0;
3552#if ENABLE_HUSH_FAST
3553 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3554//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
3555//getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
Denys Vlasenko68759ed2009-05-26 14:39:41 +02003556 /* There was neither fork nor SIGCHLD since last waitpid */
3557 /* Avoid doing waitpid syscall if possible */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003558 if (!G.we_have_children) {
3559 errno = ECHILD;
3560 return -1;
3561 }
3562 if (fg_pipe == NULL) { /* is WNOHANG set? */
3563 /* We have children, but they did not exit
3564 * or stop yet (we saw no SIGCHLD) */
3565 return 0;
3566 }
3567 /* else: !WNOHANG, waitpid will block, can't short-circuit */
3568 }
3569#endif
3570
Denis Vlasenko1359da62007-04-21 23:27:30 +00003571/* Do we do this right?
3572 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003573 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003574 * [3]+ Stopped sleep 20 | false
3575 * bash-3.00# echo $?
3576 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003577 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003578 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003579 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003580 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003581 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003582 int dead;
3583
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003584#if ENABLE_HUSH_FAST
3585 i = G.count_SIGCHLD;
3586#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003587 childpid = waitpid(-1, &status, attributes);
3588 if (childpid <= 0) {
3589 if (childpid && errno != ECHILD)
3590 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003591#if ENABLE_HUSH_FAST
3592 else { /* Until next SIGCHLD, waitpid's are useless */
Denys Vlasenkoe2df5f42009-05-26 14:34:10 +02003593 G.we_have_children = (childpid == 0);
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003594 G.handled_SIGCHLD = i;
3595//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3596 }
3597#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003598 break;
3599 }
3600 dead = WIFEXITED(status) || WIFSIGNALED(status);
3601
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003602#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003603 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003604 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003605 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3606 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003607 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003608 childpid, WTERMSIG(status), WEXITSTATUS(status));
3609 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003610 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003611 childpid, WEXITSTATUS(status));
3612#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003613 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003614 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003615 for (i = 0; i < fg_pipe->num_cmds; i++) {
3616 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3617 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003618 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003619 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003620 fg_pipe->cmds[i].pid = 0;
3621 fg_pipe->alive_cmds--;
3622 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003623 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003624 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003625 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003626 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003627 /* bash prints killing signal's name for *last*
3628 * process in pipe (prints just newline for SIGINT).
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003629 * Mimic this. Example: "sleep 5" + ^\
Denis Vlasenko40e84372009-04-18 11:23:38 +00003630 */
3631 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003632 int sig = WTERMSIG(status);
3633 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003634 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003635 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003636 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003637 fg_pipe->cmds[i].is_stopped = 1;
3638 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003639 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003640 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3641 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3642 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003643 /* All processes in fg pipe have exited or stopped */
3644/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3645 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3646 * and "killall -STOP cat" */
3647 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003648#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003649 if (fg_pipe->alive_cmds)
3650 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003651#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003652 return rcode;
3653 }
Denys Vlasenko6f226242009-06-03 14:37:30 +02003654 if (!fg_pipe->alive_cmds)
3655 return rcode;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003656 }
3657 /* There are still running processes in the fg pipe */
3658 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003659 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003660 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003661 }
3662
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003663#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003664 /* We asked to wait for bg or orphaned children */
3665 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003666 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003667 for (i = 0; i < pi->num_cmds; i++) {
3668 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003669 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003670 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003671 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003672 /* Happens when shell is used as init process (init=/bin/sh) */
3673 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003674 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003675
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003676 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003677 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003678 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003679 pi->cmds[i].pid = 0;
3680 pi->alive_cmds--;
3681 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003682 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003683 printf(JOB_STATUS_FORMAT, pi->jobid,
3684 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003685 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003686 }
3687 } else {
3688 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003689 pi->cmds[i].is_stopped = 1;
3690 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003691 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003692#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003693 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003694
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003695 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003696}
3697
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003698#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003699static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3700{
3701 pid_t p;
3702 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003703 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003704 /* Job finished, move the shell to the foreground */
3705 p = getpgrp(); /* our process group id */
3706 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3707 tcsetpgrp(G_interactive_fd, p);
3708 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003709 return rcode;
3710}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003711#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003712
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003713/* Start all the jobs, but don't wait for anything to finish.
3714 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003715 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003716 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003717 * to finish to determine the exit status of the pipe. If the pipe
3718 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003719 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003720 * return value.
3721 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003722 * Returns -1 only if started some children. IOW: we have to
3723 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003724 *
3725 * The only case when we do not need to [v]fork is when the pipe
3726 * is single, non-backgrounded, non-subshell command. Examples:
3727 * cmd ; ... { list } ; ...
3728 * cmd && ... { list } && ...
3729 * cmd || ... { list } || ...
3730 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3731 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003732 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003733 *
3734 * Cases when we must fork:
3735 * non-single: cmd | cmd
3736 * backgrounded: cmd & { list } &
3737 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003738 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003739static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003740{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003741 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003742 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003743 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003744 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003745 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003746 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003747 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003748 /* it is not always needed, but we aim to smaller code */
3749 int squirrel[] = { -1, -1, -1 };
3750 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003751
Denis Vlasenko552433b2009-04-04 19:29:21 +00003752 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003753 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003754
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003755 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003756 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003757 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003758 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003759
Denis Vlasenko552433b2009-04-04 19:29:21 +00003760 if (pi->num_cmds != 1
3761 || pi->followup == PIPE_BG
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003762 || command->cmd_type == CMD_SUBSHELL
Denis Vlasenko552433b2009-04-04 19:29:21 +00003763 ) {
3764 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003765 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003766
Denis Vlasenko552433b2009-04-04 19:29:21 +00003767 pi->alive_cmds = 1;
3768
3769 debug_printf_exec(": group:%p argv:'%s'\n",
3770 command->group, command->argv ? command->argv[0] : "NONE");
3771
3772 if (command->group) {
3773#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003774 if (command->cmd_type == CMD_FUNCDEF) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003775 /* "executing" func () { list } */
3776 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003777
Denis Vlasenkobc569742009-04-12 20:35:19 +00003778 funcp = new_function(command->argv[0]);
3779 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003780 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003781# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003782 funcp->body_as_string = command->group_as_string;
3783 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003784# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003785 command->group = NULL;
3786 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003787 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3788 funcp->parent_cmd = command;
3789 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003790
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003791 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3792 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003793 return EXIT_SUCCESS;
3794 }
3795#endif
3796 /* { list } */
3797 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003798 rcode = 1; /* exitcode if redir failed */
3799 if (setup_redirects(command, squirrel) == 0) {
3800 debug_printf_exec(": run_list\n");
3801 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003802 }
Eric Andersen04407e52001-06-07 16:42:05 +00003803 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003804 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003805 debug_leave();
3806 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003807 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003808 }
3809
Denis Vlasenko552433b2009-04-04 19:29:21 +00003810 argv = command->argv ? command->argv : (char **) &null_ptr;
3811 {
3812 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003813#if ENABLE_HUSH_FUNCTIONS
3814 const struct function *funcp;
3815#else
3816 enum { funcp = 0 };
3817#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003818 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003819 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003820
Denis Vlasenko552433b2009-04-04 19:29:21 +00003821 if (argv[command->assignment_cnt] == NULL) {
3822 /* Assignments, but no command */
3823 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003824 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003825 restore_redirects(squirrel);
3826 /* Set shell variables */
3827 while (*argv) {
3828 p = expand_string_to_string(*argv);
3829 debug_printf_exec("set shell var:'%s'->'%s'\n",
3830 *argv, p);
Denys Vlasenko295fef82009-06-03 12:47:26 +02003831 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003832 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003833 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003834 /* Do we need to flag set_local_var() errors?
3835 * "assignment to readonly var" and "putenv error"
3836 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003837 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003838 debug_leave();
3839 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003840 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003841 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003842
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003843 /* Expand the rest into (possibly) many strings each */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003844 if (0) {}
3845#if ENABLE_HUSH_BASH_COMPAT
3846 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003847 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
3848 }
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02003849#endif
Denys Vlasenko9d617c42009-06-09 18:40:52 +02003850#ifdef CMD_SINGLEWORD_NOGLOB_COND
3851 else if (command->cmd_type == CMD_SINGLEWORD_NOGLOB_COND) {
3852 argv_expanded = expand_strvec_to_strvec_singleword_noglob_cond(argv + command->assignment_cnt);
3853
3854 }
3855#endif
3856 else {
3857 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3858 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003859
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003860 x = find_builtin(argv_expanded[0]);
3861#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003862 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003863 if (!x)
3864 funcp = find_function(argv_expanded[0]);
3865#endif
3866 if (x || funcp) {
3867 if (!funcp) {
3868 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3869 debug_printf("exec with redirects only\n");
3870 rcode = setup_redirects(command, NULL);
3871 goto clean_up_and_ret1;
3872 }
Eric Andersen25f27032001-04-26 23:22:31 +00003873 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003874 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003875 * This is perfect for work that comes after exec().
3876 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003877 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003878 rcode = setup_redirects(command, squirrel);
3879 if (rcode == 0) {
3880 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003881 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003882 if (!funcp) {
3883 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003884 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003885 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003886 fflush(NULL);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003887 }
3888#if ENABLE_HUSH_FUNCTIONS
3889 else {
Denys Vlasenko295fef82009-06-03 12:47:26 +02003890# if ENABLE_HUSH_LOCAL
3891 struct variable **sv;
3892 sv = G.shadowed_vars_pp;
3893 G.shadowed_vars_pp = &old_vars;
3894# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003895 debug_printf_exec(": function '%s' '%s'...\n",
3896 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003897 rcode = run_function(funcp, argv_expanded) & 0xff;
Denys Vlasenko295fef82009-06-03 12:47:26 +02003898# if ENABLE_HUSH_LOCAL
3899 G.shadowed_vars_pp = sv;
3900# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003901 }
3902#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003903 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003904#if ENABLE_FEATURE_SH_STANDALONE
3905 clean_up_and_ret:
3906#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003907 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003908 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003909 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003910 clean_up_and_ret1:
3911 free(argv_expanded);
3912 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003913 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003914 debug_printf_exec("run_pipe return %d\n", rcode);
3915 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003916 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003917
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003918#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003919 i = find_applet_by_name(argv_expanded[0]);
3920 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003921 rcode = setup_redirects(command, squirrel);
3922 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003923 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003924 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003925 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003926 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003927 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003928 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003929 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003930 }
3931#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003932 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003933 }
3934
Denis Vlasenko552433b2009-04-04 19:29:21 +00003935 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003936 /* NB: argv_expanded may already be created, and that
3937 * might include `cmd` runs! Do not rerun it! We *must*
3938 * use argv_expanded if it's non-NULL */
3939
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003940 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003941 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003942 nextin = 0;
3943
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003944 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003945 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003946#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003947 volatile nommu_save_t nommu_save;
3948 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003949 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003950 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003951 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003952#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003953 command = &(pi->cmds[i]);
3954 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003955 debug_printf_exec(": pipe member '%s' '%s'...\n",
3956 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003957 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003958 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003959 }
Eric Andersen25f27032001-04-26 23:22:31 +00003960
3961 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003962 pipefds.rd = 0;
3963 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003964 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003965 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003966
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003967 command->pid = BB_MMU ? fork() : vfork();
3968 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003969#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003970 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003971
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003972 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003973 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003974 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003975 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003976 pgrp = pi->pgrp;
3977 if (pgrp < 0) /* true for 1st process only */
3978 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003979 if (setpgid(0, pgrp) == 0
3980 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04003981 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003982 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003983 /* We do it in *every* child, not just first,
3984 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003985 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003986 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003987 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003988#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003989 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3990 /* 1st cmd in backgrounded pipe
3991 * should have its stdin /dev/null'ed */
3992 close(0);
3993 if (open(bb_dev_null, O_RDONLY))
3994 xopen("/", O_RDONLY);
3995 } else {
3996 xmove_fd(nextin, 0);
3997 }
3998 xmove_fd(pipefds.wr, 1);
3999 if (pipefds.rd > 1)
4000 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00004001 /* Like bash, explicit redirects override pipes,
4002 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00004003 if (setup_redirects(command, NULL))
4004 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00004005
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004006 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004007 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
4008
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004009 /* Stores to nommu_save list of env vars putenv'ed
4010 * (NOMMU, on MMU we don't need that) */
4011 /* cast away volatility... */
4012 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004013 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00004014 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004015
Denis Vlasenkof9375282009-04-05 19:13:39 +00004016 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004017#if ENABLE_HUSH_FAST
4018 G.count_SIGCHLD++;
4019//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
4020#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004021 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004022#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004023 /* Clean up after vforked child */
4024 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004025 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02004026 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02004027 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004028#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004029 free(argv_expanded);
4030 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004031 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004032 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00004033 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004034 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004035 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004036#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004037 /* Second and next children need to know pid of first one */
4038 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004039 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004040#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004041 }
Eric Andersen25f27032001-04-26 23:22:31 +00004042
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004043 if (i)
4044 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004045 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004046 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004047 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00004048 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00004049 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00004050
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004051 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004052 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00004053 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
4054 return 1;
4055 }
4056
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004057 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004058 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00004059 return -1;
4060}
4061
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004062#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004063static void debug_print_tree(struct pipe *pi, int lvl)
4064{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004065 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004066 [PIPE_SEQ] = "SEQ",
4067 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004068 [PIPE_OR ] = "OR" ,
4069 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004070 };
4071 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004072 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004073#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004074 [RES_IF ] = "IF" ,
4075 [RES_THEN ] = "THEN" ,
4076 [RES_ELIF ] = "ELIF" ,
4077 [RES_ELSE ] = "ELSE" ,
4078 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004079#endif
4080#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004081 [RES_FOR ] = "FOR" ,
4082 [RES_WHILE] = "WHILE",
4083 [RES_UNTIL] = "UNTIL",
4084 [RES_DO ] = "DO" ,
4085 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004086#endif
4087#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004088 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00004089#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004090#if ENABLE_HUSH_CASE
4091 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004092 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004093 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004094 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004095 [RES_ESAC ] = "ESAC" ,
4096#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00004097 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004098 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004099 };
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004100 static const char *const CMDTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004101 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00004102 "()",
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004103 "[noglob]",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004104#if ENABLE_HUSH_FUNCTIONS
4105 "func()",
4106#endif
4107 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004108
4109 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004110
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004111 pin = 0;
4112 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004113 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
4114 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004115 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004116 while (prn < pi->num_cmds) {
4117 struct command *command = &pi->cmds[prn];
4118 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004119
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004120 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004121 lvl*2, "", prn,
4122 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004123 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004124 fprintf(stderr, " group %s: (argv=%p)\n",
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004125 CMDTYPE[command->cmd_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004126 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004127 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004128 prn++;
4129 continue;
4130 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004131 if (argv) while (*argv) {
4132 fprintf(stderr, " '%s'", *argv);
4133 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00004134 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004135 fprintf(stderr, "\n");
4136 prn++;
4137 }
4138 pi = pi->next;
4139 pin++;
4140 }
4141}
4142#endif
4143
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004144/* NB: called by pseudo_exec, and therefore must not modify any
4145 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004146static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004147{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004148#if ENABLE_HUSH_CASE
4149 char *case_word = NULL;
4150#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004151#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004152 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004153 char **for_lcur = NULL;
4154 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00004155#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004156 smallint last_followup;
4157 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00004158#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004159 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004160#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004161 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004162#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00004163#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004164 smallint rword; /* enum reserved_style */
4165 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004166#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004167
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004168 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004169 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00004170
Denis Vlasenko06810332007-05-21 23:30:54 +00004171#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004172 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004173 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
4174 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004175 continue;
4176 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004177 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004178 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004179 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004180 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004181 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004182 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004183 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004184 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004185 continue;
4186 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004187 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
4188 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004189 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004190 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004191 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004192 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004193 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004194 }
4195 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004196#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004197
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004198 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00004199 * in order to return, no direct "return" statements please.
4200 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004201
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004202#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00004203 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004204#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004205
Denis Vlasenko0e151382009-04-06 18:40:31 +00004206#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004207 rword = RES_NONE;
4208 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004209#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004210 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004211 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004212
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004213 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004214 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00004215 if (G.flag_SIGINT)
4216 break;
4217
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004218 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004219 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
4220 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00004221#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00004222 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004223 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00004224 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004225 /* start of a loop: remember where loop starts */
4226 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004227 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004228 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004229#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004230 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00004231 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004232 if ((rcode == 0 && last_followup == PIPE_OR)
4233 || (rcode != 0 && last_followup == PIPE_AND)
4234 ) {
4235 /* It is "<true> || CMD" or "<false> && CMD"
4236 * and we should not execute CMD */
4237 debug_printf_exec("skipped cmd because of || or &&\n");
4238 last_followup = pi->followup;
4239 continue;
4240 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004241 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004242 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00004243 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00004244#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004245 if (cond_code) {
4246 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00004247 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004248 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004249 /* "if <false> THEN cmd": skip cmd */
4250 continue;
4251 }
4252 } else {
4253 if (rword == RES_ELSE || rword == RES_ELIF) {
4254 /* "if <true> then ... ELSE/ELIF cmd":
4255 * skip cmd and all following ones */
4256 break;
4257 }
4258 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004259#endif
4260#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004261 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004262 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00004263 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004264
4265 static const char encoded_dollar_at[] ALIGN1 = {
4266 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
4267 }; /* encoded representation of "$@" */
4268 static const char *const encoded_dollar_at_argv[] = {
4269 encoded_dollar_at, NULL
4270 }; /* argv list with one element: "$@" */
4271 char **vals;
4272
4273 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00004274 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004275 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004276 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004277 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004278 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004279 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004280 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004281 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004282 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004283 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004284 debug_print_strings("for_list made from", vals);
4285 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004286 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004287 debug_print_strings("for_list", for_list);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004288 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004289 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004290 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004291 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004292 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004293 for_lcur = NULL;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004294 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004295 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004296 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004297 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denys Vlasenko295fef82009-06-03 12:47:26 +02004298 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 +02004299 continue;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004300 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004301 if (rword == RES_IN) {
4302 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4303 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004304 if (rword == RES_DONE) {
4305 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004306 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004307#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004308#if ENABLE_HUSH_CASE
4309 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004310 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004311 continue;
4312 }
4313 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004314 char **argv;
4315
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004316 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4317 break;
4318 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004319 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004320 while (*argv) {
4321 char *pattern = expand_string_to_string(*argv);
4322 /* TODO: which FNM_xxx flags to use? */
4323 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4324 free(pattern);
4325 if (cond_code == 0) { /* match! we will execute this branch */
4326 free(case_word); /* make future "word)" stop */
4327 case_word = NULL;
4328 break;
4329 }
4330 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004331 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004332 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004333 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004334 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004335 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004336 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004337 }
4338#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004339 /* Just pressing <enter> in shell should check for jobs.
4340 * OTOH, in non-interactive shell this is useless
4341 * and only leads to extra job checks */
4342 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004343 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004344 goto check_jobs_and_continue;
4345 continue;
4346 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004347
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004348 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004349 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004350 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004351 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004352 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004353 {
4354 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004355#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004356 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004357#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004358 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4359 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004360 /* We ran a builtin, function, or group.
4361 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004362 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004363 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004364 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004365 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004366#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004367 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004368 if (G.flag_break_continue) {
4369 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004370 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004371 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004372 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004373 G.depth_break_continue--;
4374 if (G.depth_break_continue == 0)
4375 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004376 /* else: e.g. "continue 2" should *break* once, *then* continue */
4377 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004378 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004379 goto check_jobs_and_break;
4380 /* "continue": simulate end of loop */
4381 rword = RES_DONE;
4382 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004383 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004384#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004385#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenko673e9452009-05-27 14:39:35 +02004386 if (G.flag_return_in_progress == 1) {
4387 /* same as "goto check_jobs_and_break" */
4388 checkjobs(NULL);
4389 break;
4390 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004391#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004392 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004393 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004394 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004395 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4396 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004397 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004398#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004399 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004400 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004401#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004402 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004403 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004404 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004405#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004406 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004407 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004408 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004409 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004410 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004411 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004412#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004413 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004414 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004415 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004416 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004417 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004418 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004419 }
4420 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004421
4422 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004423#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004424 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004425 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004426#endif
4427#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004428 /* Beware of "while false; true; do ..."! */
4429 if (pi->next && pi->next->res_word == RES_DO) {
4430 if (rword == RES_WHILE) {
4431 if (rcode) {
4432 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004433 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004434 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4435 goto check_jobs_and_break;
4436 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004437 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004438 if (rword == RES_UNTIL) {
4439 if (!rcode) {
4440 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004441 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004442 checkjobs(NULL);
4443 break;
4444 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004445 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004446 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004447#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004448
4449 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004450 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004451 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004452
4453#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004454 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004455#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004456#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004457 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004458 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004459 free(for_list);
4460#endif
4461#if ENABLE_HUSH_CASE
4462 free(case_word);
4463#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004464 debug_leave();
4465 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004466 return rcode;
4467}
4468
Eric Andersen25f27032001-04-26 23:22:31 +00004469/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004470static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004471{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004472 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004473 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004474 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004475 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004476 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004477 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004478 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004479 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004480 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004481 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004482 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004483 return rcode;
4484}
4485
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004486
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004487static struct pipe *new_pipe(void)
4488{
Eric Andersen25f27032001-04-26 23:22:31 +00004489 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004490 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004491 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004492 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004493 return pi;
4494}
4495
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004496/* Command (member of a pipe) is complete, or we start a new pipe
4497 * if ctx->command is NULL.
4498 * No errors possible here.
4499 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004500static int done_command(struct parse_context *ctx)
4501{
4502 /* The command is really already in the pipe structure, so
4503 * advance the pipe counter and make a new, null command. */
4504 struct pipe *pi = ctx->pipe;
4505 struct command *command = ctx->command;
4506
4507 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004508 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004509 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004510 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004511 }
4512 pi->num_cmds++;
4513 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004514 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004515 } else {
4516 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4517 }
4518
4519 /* Only real trickiness here is that the uncommitted
4520 * command structure is not counted in pi->num_cmds. */
4521 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004522 ctx->command = command = &pi->cmds[pi->num_cmds];
4523 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004524 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004525 return pi->num_cmds; /* used only for 0/nonzero check */
4526}
4527
4528static void done_pipe(struct parse_context *ctx, pipe_style type)
4529{
4530 int not_null;
4531
4532 debug_printf_parse("done_pipe entered, followup %d\n", type);
4533 /* Close previous command */
4534 not_null = done_command(ctx);
4535 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004536#if HAS_KEYWORDS
4537 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4538 ctx->ctx_inverted = 0;
4539 ctx->pipe->res_word = ctx->ctx_res_w;
4540#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004541
4542 /* Without this check, even just <enter> on command line generates
4543 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004544 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004545 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004546#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004547 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004548#endif
4549#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004550 || ctx->ctx_res_w == RES_DONE
4551 || ctx->ctx_res_w == RES_FOR
4552 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004553#endif
4554#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004555 || ctx->ctx_res_w == RES_ESAC
4556#endif
4557 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004558 struct pipe *new_p;
4559 debug_printf_parse("done_pipe: adding new pipe: "
4560 "not_null:%d ctx->ctx_res_w:%d\n",
4561 not_null, ctx->ctx_res_w);
4562 new_p = new_pipe();
4563 ctx->pipe->next = new_p;
4564 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004565 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004566 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004567 * This is used to control execution.
4568 * RES_FOR and RES_IN are NOT sticky (needed to support
4569 * cases where variable or value happens to match a keyword):
4570 */
4571#if ENABLE_HUSH_LOOPS
4572 if (ctx->ctx_res_w == RES_FOR
4573 || ctx->ctx_res_w == RES_IN)
4574 ctx->ctx_res_w = RES_NONE;
4575#endif
4576#if ENABLE_HUSH_CASE
4577 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004578 ctx->ctx_res_w = RES_CASE_BODY;
4579 if (ctx->ctx_res_w == RES_CASE)
4580 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004581#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004582 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004583 /* Create the memory for command, roughly:
4584 * ctx->pipe->cmds = new struct command;
4585 * ctx->command = &ctx->pipe->cmds[0];
4586 */
4587 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004588 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004589 }
4590 debug_printf_parse("done_pipe return\n");
4591}
4592
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004593static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004594{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004595 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004596 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004597 /* Create the memory for command, roughly:
4598 * ctx->pipe->cmds = new struct command;
4599 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004600 */
4601 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004602}
4603
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004604/* If a reserved word is found and processed, parse context is modified
4605 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004606 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004607#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004608struct reserved_combo {
4609 char literal[6];
4610 unsigned char res;
4611 unsigned char assignment_flag;
4612 int flag;
4613};
4614enum {
4615 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004616#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004617 FLAG_IF = (1 << RES_IF ),
4618 FLAG_THEN = (1 << RES_THEN ),
4619 FLAG_ELIF = (1 << RES_ELIF ),
4620 FLAG_ELSE = (1 << RES_ELSE ),
4621 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004622#endif
4623#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004624 FLAG_FOR = (1 << RES_FOR ),
4625 FLAG_WHILE = (1 << RES_WHILE),
4626 FLAG_UNTIL = (1 << RES_UNTIL),
4627 FLAG_DO = (1 << RES_DO ),
4628 FLAG_DONE = (1 << RES_DONE ),
4629 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004630#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004631#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004632 FLAG_MATCH = (1 << RES_MATCH),
4633 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004634#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004635 FLAG_START = (1 << RES_XXXX ),
4636};
4637
4638static const struct reserved_combo* match_reserved_word(o_string *word)
4639{
Eric Andersen25f27032001-04-26 23:22:31 +00004640 /* Mostly a list of accepted follow-up reserved words.
4641 * FLAG_END means we are done with the sequence, and are ready
4642 * to turn the compound list into a command.
4643 * FLAG_START means the word must start a new compound list.
4644 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004645 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004646#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004647 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4648 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4649 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4650 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4651 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4652 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004653#endif
4654#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004655 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4656 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4657 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4658 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4659 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4660 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004661#endif
4662#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004663 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4664 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004665#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004666 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004667 const struct reserved_combo *r;
4668
4669 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4670 if (strcmp(word->data, r->literal) == 0)
4671 return r;
4672 }
4673 return NULL;
4674}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004675/* Return 0: not a keyword, 1: keyword
4676 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004677static int reserved_word(o_string *word, struct parse_context *ctx)
4678{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004679#if ENABLE_HUSH_CASE
4680 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004681 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004682 };
4683#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004684 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004685
Denis Vlasenkobb929512009-04-16 10:59:40 +00004686 if (word->o_quoted)
4687 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004688 r = match_reserved_word(word);
4689 if (!r)
4690 return 0;
4691
4692 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004693#if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004694 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4695 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004696 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004697 } else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004698#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004699 if (r->flag == 0) { /* '!' */
4700 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004701 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004702 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004703 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004704 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004705 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004706 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004707 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004708 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004709
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004710 old = xmalloc(sizeof(*old));
4711 debug_printf_parse("push stack %p\n", old);
4712 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004713 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004714 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004715 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004716 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004717 ctx->ctx_res_w = RES_SNTX;
4718 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004719 } else {
4720 /* "{...} fi" is ok. "{...} if" is not
4721 * Example:
4722 * if { echo foo; } then { echo bar; } fi */
4723 if (ctx->command->group)
4724 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004725 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004726
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004727 ctx->ctx_res_w = r->res;
4728 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004729 word->o_assignment = r->assignment_flag;
4730
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004731 if (ctx->old_flag & FLAG_END) {
4732 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004733
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004734 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004735 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004736 old = ctx->stack;
4737 old->command->group = ctx->list_head;
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004738 old->command->cmd_type = CMD_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004739#if !BB_MMU
4740 o_addstr(&old->as_string, ctx->as_string.data);
4741 o_free_unsafe(&ctx->as_string);
4742 old->command->group_as_string = xstrdup(old->as_string.data);
4743 debug_printf_parse("pop, remembering as:'%s'\n",
4744 old->command->group_as_string);
4745#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004746 *ctx = *old; /* physical copy */
4747 free(old);
4748 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004749 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004750}
Denis Vlasenko06810332007-05-21 23:30:54 +00004751#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004752
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004753/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004754 * Normal return is 0. Syntax errors return 1.
4755 * Note: on return, word is reset, but not o_free'd!
4756 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004757static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004758{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004759 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004760
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004761 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004762 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004763 debug_printf_parse("done_word return 0: true null, ignored\n");
4764 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004765 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004766
Eric Andersen25f27032001-04-26 23:22:31 +00004767 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004768 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4769 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004770 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4771 * "2.7 Redirection
4772 * ...the word that follows the redirection operator
4773 * shall be subjected to tilde expansion, parameter expansion,
4774 * command substitution, arithmetic expansion, and quote
4775 * removal. Pathname expansion shall not be performed
4776 * on the word by a non-interactive shell; an interactive
4777 * shell may perform it, but shall do so only when
4778 * the expansion would result in one word."
4779 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004780 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004781 /* Cater for >\file case:
4782 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4783 * Same with heredocs:
4784 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4785 */
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02004786 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
4787 unbackslash(ctx->pending_redirect->rd_filename);
4788 /* Is it <<"HEREDOC"? */
4789 if (word->o_quoted) {
4790 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4791 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004792 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004793 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004794 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004795 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004796 /* If this word wasn't an assignment, next ones definitely
4797 * can't be assignments. Even if they look like ones. */
4798 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4799 && word->o_assignment != WORD_IS_KEYWORD
4800 ) {
4801 word->o_assignment = NOT_ASSIGNMENT;
4802 } else {
4803 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4804 command->assignment_cnt++;
4805 word->o_assignment = MAYBE_ASSIGNMENT;
4806 }
4807
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004808#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004809# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004810 if (ctx->ctx_dsemicolon
4811 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4812 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004813 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004814 /* ctx->ctx_res_w = RES_MATCH; */
4815 ctx->ctx_dsemicolon = 0;
4816 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004817# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004818 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004819# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004820 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4821 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004822# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004823# if ENABLE_HUSH_CASE
4824 && ctx->ctx_res_w != RES_CASE
4825# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004826 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004827 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004828 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004829 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004830 debug_printf_parse("done_word return %d\n",
4831 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004832 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004833 }
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004834# ifdef CMD_SINGLEWORD_NOGLOB_COND
4835 if (strcmp(word->data, "export") == 0
4836# if ENABLE_HUSH_LOCAL
4837 || strcmp(word->data, "local") == 0
4838# endif
4839 ) {
4840 command->cmd_type = CMD_SINGLEWORD_NOGLOB_COND;
4841 } else
4842# endif
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004843# if ENABLE_HUSH_BASH_COMPAT
Denys Vlasenko9d617c42009-06-09 18:40:52 +02004844 if (strcmp(word->data, "[[") == 0) {
4845 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
4846 }
4847 /* fall through */
Denys Vlasenko9ca656b2009-06-10 13:39:35 +02004848# endif
Eric Andersen25f27032001-04-26 23:22:31 +00004849 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004850#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004851 if (command->group) {
4852 /* "{ echo foo; } echo bar" - bad */
4853 syntax_error_at(word->data);
4854 debug_printf_parse("done_word return 1: syntax error, "
4855 "groups and arglists don't mix\n");
4856 return 1;
4857 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004858 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004859 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4860 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004861 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004862 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004863 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004864 char *p = word->data;
4865 while (p[0] == SPECIAL_VAR_SYMBOL
4866 && (p[1] & 0x7f) == '@'
4867 && p[2] == SPECIAL_VAR_SYMBOL
4868 ) {
4869 p += 3;
4870 }
4871 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004872 /* saw no "$@", or not only "$@" but some
4873 * real text is there too */
4874 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004875 * e.g. "", $empty"" etc to not disappear */
4876 o_addchr(word, SPECIAL_VAR_SYMBOL);
4877 o_addchr(word, SPECIAL_VAR_SYMBOL);
4878 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004879 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004880 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004881 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004882 }
Eric Andersen25f27032001-04-26 23:22:31 +00004883
Denis Vlasenko06810332007-05-21 23:30:54 +00004884#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004885 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004886 if (word->o_quoted
4887 || !is_well_formed_var_name(command->argv[0], '\0')
4888 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004889 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004890 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004891 return 1;
4892 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004893 /* Force FOR to have just one word (variable name) */
4894 /* NB: basically, this makes hush see "for v in ..."
4895 * syntax as if it is "for v; in ...". FOR and IN become
4896 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004897 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004898 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004899#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004900#if ENABLE_HUSH_CASE
4901 /* Force CASE to have just one word */
4902 if (ctx->ctx_res_w == RES_CASE) {
4903 done_pipe(ctx, PIPE_SEQ);
4904 }
4905#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004906
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004907 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004908
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004909 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004910 return 0;
4911}
4912
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004913
4914/* Peek ahead in the input to find out if we have a "&n" construct,
4915 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004916 * Return:
4917 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4918 * REDIRFD_SYNTAX_ERR if syntax error,
4919 * REDIRFD_TO_FILE if no & was seen,
4920 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004921 */
4922#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004923#define parse_redir_right_fd(as_string, input) \
4924 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004925#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004926static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004927{
4928 int ch, d, ok;
4929
4930 ch = i_peek(input);
4931 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004932 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004933
4934 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004935 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004936 ch = i_peek(input);
4937 if (ch == '-') {
4938 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004939 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004940 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004941 }
4942 d = 0;
4943 ok = 0;
4944 while (ch != EOF && isdigit(ch)) {
4945 d = d*10 + (ch-'0');
4946 ok = 1;
4947 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004948 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004949 ch = i_peek(input);
4950 }
4951 if (ok) return d;
4952
4953//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4954
4955 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004956 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004957}
4958
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004959/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004960 */
4961static int parse_redirect(struct parse_context *ctx,
4962 int fd,
4963 redir_type style,
4964 struct in_str *input)
4965{
4966 struct command *command = ctx->command;
4967 struct redir_struct *redir;
4968 struct redir_struct **redirp;
4969 int dup_num;
4970
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004971 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004972 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004973 /* Check for a '>&1' type redirect */
4974 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4975 if (dup_num == REDIRFD_SYNTAX_ERR)
4976 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004977 } else {
4978 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004979 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004980 if (dup_num) { /* <<-... */
4981 ch = i_getch(input);
4982 nommu_addchr(&ctx->as_string, ch);
4983 ch = i_peek(input);
4984 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004985 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004986
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004987 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004988 int ch = i_peek(input);
4989 if (ch == '|') {
4990 /* >|FILE redirect ("clobbering" >).
4991 * Since we do not support "set -o noclobber" yet,
4992 * >| and > are the same for now. Just eat |.
4993 */
4994 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004995 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004996 }
4997 }
4998
4999 /* Create a new redir_struct and append it to the linked list */
5000 redirp = &command->redirects;
5001 while ((redir = *redirp) != NULL) {
5002 redirp = &(redir->next);
5003 }
5004 *redirp = redir = xzalloc(sizeof(*redir));
5005 /* redir->next = NULL; */
5006 /* redir->rd_filename = NULL; */
5007 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005008 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005009
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005010 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
5011 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005012
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005013 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005014 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005015 /* Erik had a check here that the file descriptor in question
5016 * is legit; I postpone that to "run time"
5017 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005018 debug_printf_parse("duplicating redirect '%d>&%d'\n",
5019 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005020 } else {
5021 /* Set ctx->pending_redirect, so we know what to do at the
5022 * end of the next parsed word. */
5023 ctx->pending_redirect = redir;
5024 }
5025 return 0;
5026}
5027
Eric Andersen25f27032001-04-26 23:22:31 +00005028/* If a redirect is immediately preceded by a number, that number is
5029 * supposed to tell which file descriptor to redirect. This routine
5030 * looks for such preceding numbers. In an ideal world this routine
5031 * needs to handle all the following classes of redirects...
5032 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
5033 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
5034 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
5035 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005036 *
5037 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
5038 * "2.7 Redirection
5039 * ... If n is quoted, the number shall not be recognized as part of
5040 * the redirection expression. For example:
5041 * echo \2>a
5042 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005043 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005044 *
5045 * A -1 return means no valid number was found,
5046 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00005047 */
5048static int redirect_opt_num(o_string *o)
5049{
5050 int num;
5051
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005052 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005053 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005054 num = bb_strtou(o->data, NULL, 10);
5055 if (errno || num < 0)
5056 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005057 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00005058 return num;
5059}
5060
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005061#if BB_MMU
5062#define fetch_till_str(as_string, input, word, skip_tabs) \
5063 fetch_till_str(input, word, skip_tabs)
5064#endif
5065static char *fetch_till_str(o_string *as_string,
5066 struct in_str *input,
5067 const char *word,
5068 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005069{
5070 o_string heredoc = NULL_O_STRING;
5071 int past_EOL = 0;
5072 int ch;
5073
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005074 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005075 while (1) {
5076 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005077 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005078 if (ch == '\n') {
5079 if (strcmp(heredoc.data + past_EOL, word) == 0) {
5080 heredoc.data[past_EOL] = '\0';
5081 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
5082 return heredoc.data;
5083 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005084 do {
5085 o_addchr(&heredoc, ch);
5086 past_EOL = heredoc.length;
5087 jump_in:
5088 do {
5089 ch = i_getch(input);
5090 nommu_addchr(as_string, ch);
5091 } while (skip_tabs && ch == '\t');
5092 } while (ch == '\n');
5093 }
5094 if (ch == EOF) {
5095 o_free_unsafe(&heredoc);
5096 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005097 }
5098 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005099 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005100 }
5101}
5102
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005103/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
5104 * and load them all. There should be exactly heredoc_cnt of them.
5105 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005106static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
5107{
5108 struct pipe *pi = ctx->list_head;
5109
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005110 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005111 int i;
5112 struct command *cmd = pi->cmds;
5113
5114 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
5115 pi->num_cmds,
5116 cmd->argv ? cmd->argv[0] : "NONE");
5117 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005118 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005119
5120 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
5121 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005122 while (redir) {
5123 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005124 char *p;
5125
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005126 redir->rd_type = REDIRECT_HEREDOC2;
Denys Vlasenko764b2f02009-06-07 16:05:04 +02005127 /* redir->rd_dup is (ab)used to indicate <<- */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005128 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005129 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005130 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005131 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005132 return 1;
5133 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005134 free(redir->rd_filename);
5135 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005136 heredoc_cnt--;
5137 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005138 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005139 }
5140 cmd++;
5141 }
5142 pi = pi->next;
5143 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005144#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005145 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005146 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005147 bb_error_msg_and_die("heredoc BUG 2");
5148#endif
5149 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005150}
5151
5152
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005153#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005154static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005155{
5156 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005157 int pid, channel[2];
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005158#if !BB_MMU
5159 char **to_free;
5160#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005161
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00005162 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00005163 pid = BB_MMU ? fork() : vfork();
5164 if (pid < 0)
5165 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005166
Denis Vlasenko05743d72008-02-10 12:10:08 +00005167 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005168 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00005169 /* Process substitution is not considered to be usual
5170 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00005171 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5172 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00005173 bb_signals(0
5174 + (1 << SIGTSTP)
5175 + (1 << SIGTTIN)
5176 + (1 << SIGTTOU)
5177 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005178 close(channel[0]); /* NB: close _first_, then move fd! */
5179 xmove_fd(channel[1], 1);
5180 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005181 IF_HUSH_JOB(G.run_list_level = 1;)
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005182#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005183 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005184 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005185 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005186#else
5187 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00005188 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5189 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005190 * echo OK
5191 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005192 re_execute_shell(&to_free,
5193 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005194 G.global_argv[0],
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02005195 G.global_argv + 1,
5196 NULL);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005197#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005198 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005199
5200 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02005201#if ENABLE_HUSH_FAST
5202 G.count_SIGCHLD++;
5203//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);
5204#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005205 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00005206#if !BB_MMU
5207 free(to_free);
5208#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005209 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00005210 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00005211 return pf;
5212}
5213
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00005214/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005215static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005216{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005217 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00005218 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005219 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005220
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005221 pf = generate_stream_from_string(s);
5222 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00005223 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005224 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00005225
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005226 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005227 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005228 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005229 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005230 if (ch == '\n') {
5231 eol_cnt++;
5232 continue;
5233 }
5234 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00005235 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00005236 eol_cnt--;
5237 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00005238 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005239 }
5240
5241 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005242 /* Note: we got EOF, and we just close the read end of the pipe.
5243 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005244 * Try these:
5245 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
5246 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005247 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00005248 fclose(pf);
5249 debug_printf("closed FILE from child. return 0\n");
5250 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005251}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005252#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005253
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005254static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00005255 struct in_str *input, int ch)
5256{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005257 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005258 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005259 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005260 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005261 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005262 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005263
5264 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005265#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005266 if (ch == '(' && !dest->o_quoted) {
5267 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00005268 if (done_word(dest, ctx))
5269 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005270 if (!command->argv)
5271 goto skip; /* (... */
5272 if (command->argv[1]) { /* word word ... (... */
5273 syntax_error_unexpected_ch('(');
5274 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005275 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005276 /* it is "word(..." or "word (..." */
5277 do
5278 ch = i_getch(input);
5279 while (ch == ' ' || ch == '\t');
5280 if (ch != ')') {
5281 syntax_error_unexpected_ch(ch);
5282 return 1;
5283 }
5284 nommu_addchr(&ctx->as_string, ch);
5285 do
5286 ch = i_getch(input);
5287 while (ch == ' ' || ch == '\t' || ch == '\n');
5288 if (ch != '{') {
5289 syntax_error_unexpected_ch(ch);
5290 return 1;
5291 }
5292 nommu_addchr(&ctx->as_string, ch);
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005293 command->cmd_type = CMD_FUNCDEF;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005294 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005295 }
5296#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005297 if (command->argv /* word [word]{... */
5298 || dest->length /* word{... */
5299 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005300 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005301 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005302 debug_printf_parse("parse_group return 1: "
5303 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005304 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005305 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005306
5307#if ENABLE_HUSH_FUNCTIONS
5308 skip:
5309#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005310 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005311 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005312 endch = ')';
Denys Vlasenko9d617c42009-06-09 18:40:52 +02005313 command->cmd_type = CMD_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005314 } else {
5315 /* bash does not allow "{echo...", requires whitespace */
5316 ch = i_getch(input);
5317 if (ch != ' ' && ch != '\t' && ch != '\n') {
5318 syntax_error_unexpected_ch(ch);
5319 return 1;
5320 }
5321 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005322 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005323
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005324 {
5325#if !BB_MMU
5326 char *as_string = NULL;
5327#endif
5328 pipe_list = parse_stream(&as_string, input, endch);
5329#if !BB_MMU
5330 if (as_string)
5331 o_addstr(&ctx->as_string, as_string);
5332#endif
5333 /* empty ()/{} or parse error? */
5334 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005335 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005336#if !BB_MMU
5337 free(as_string);
5338#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005339 debug_printf_parse("parse_group return 1: "
5340 "parse_stream returned %p\n", pipe_list);
5341 return 1;
5342 }
5343 command->group = pipe_list;
5344#if !BB_MMU
5345 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5346 command->group_as_string = as_string;
5347 debug_printf_parse("end of group, remembering as:'%s'\n",
5348 command->group_as_string);
5349#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005350 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005351 debug_printf_parse("parse_group return 0\n");
5352 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005353 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005354}
5355
Mike Frysinger98c52642009-04-02 10:02:37 +00005356#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005357/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005358static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005359/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005360static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005361{
5362 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005363 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005364 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005365 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005366 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005367 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005368 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005369 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005370 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005371 }
5372}
5373/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005374static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005375{
5376 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005377 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005378 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005379 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005380 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005381 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005382 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005383 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005384 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005385 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005386 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005387 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005388 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005389 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005390 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005391 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005392 continue;
5393 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005394 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005395 }
5396}
5397/* Process `cmd` - copy contents until "`" is seen. Complicated by
5398 * \` quoting.
5399 * "Within the backquoted style of command substitution, backslash
5400 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5401 * The search for the matching backquote shall be satisfied by the first
5402 * backquote found without a preceding backslash; during this search,
5403 * if a non-escaped backquote is encountered within a shell comment,
5404 * a here-document, an embedded command substitution of the $(command)
5405 * form, or a quoted string, undefined results occur. A single-quoted
5406 * or double-quoted string that begins, but does not end, within the
5407 * "`...`" sequence produces undefined results."
5408 * Example Output
5409 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5410 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005411static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005412{
5413 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005414 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005415 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005416 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005417 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005418 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005419 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005420 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005421 if (ch == '\\') {
5422 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005423 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005424 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005425 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005426 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005427 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005428 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005429 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005430 ch = ch2;
5431 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005432 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005433 }
5434}
5435/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5436 * quoting and nested ()s.
5437 * "With the $(command) style of command substitution, all characters
5438 * following the open parenthesis to the matching closing parenthesis
5439 * constitute the command. Any valid shell script can be used for command,
5440 * except a script consisting solely of redirections which produces
5441 * unspecified results."
5442 * Example Output
5443 * echo $(echo '(TEST)' BEST) (TEST) BEST
5444 * echo $(echo 'TEST)' BEST) TEST) BEST
5445 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5446 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005447static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005448{
5449 int count = 0;
5450 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005451 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005452 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005453 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005454 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005455 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005456 if (ch == '(')
5457 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005458 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005459 if (--count < 0) {
5460 if (!dbl)
5461 break;
5462 if (i_peek(input) == ')') {
5463 i_getch(input);
5464 break;
5465 }
5466 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005467 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005468 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005469 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005470 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005471 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005472 continue;
5473 }
5474 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005475 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005476 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005477 continue;
5478 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005479 if (ch == '\\') {
5480 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005481 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005482 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005483 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005484 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005485 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005486 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005487 continue;
5488 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005489 }
5490}
Mike Frysinger98c52642009-04-02 10:02:37 +00005491#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005492
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005493/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005494#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005495#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005496 handle_dollar(dest, input)
5497#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005498static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005499 o_string *dest,
5500 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005501{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005502 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005503 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005504
5505 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005506 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005507 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005508 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005509 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005510 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005511 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005512 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005513 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005514 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005515 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005516 if (!isalnum(ch) && ch != '_')
5517 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005518 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005519 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005520 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005521 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005522 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005523 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005524 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005525 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005526 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005527 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005528 o_addchr(dest, ch | quote_mask);
5529 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005530 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005531 case '$': /* pid */
5532 case '!': /* last bg pid */
5533 case '?': /* last exit code */
5534 case '#': /* number of args */
5535 case '*': /* args */
5536 case '@': /* args */
5537 goto make_one_char_var;
5538 case '{': {
5539 bool first_char, all_digits;
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005540 int expansion;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005541
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005542 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005543 nommu_addchr(as_string, ch);
Mike Frysingeref3e7fd2009-06-01 14:13:39 -04005544 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5545
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005546 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005547 expansion = 0;
5548 first_char = true;
5549 all_digits = false;
5550 while (1) {
5551 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005552 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005553 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005554 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005555 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005556
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005557 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005558 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005559 /* ${#var}: length of var contents */
5560 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005561 }
5562 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005563 all_digits = true;
5564 goto char_ok;
5565 }
Mike Frysingerdc3bc402009-06-01 14:09:09 -04005566 /* They're being verbose and doing ${?} */
5567 if (i_peek(input) == '}' && strchr("$!?#*@_", ch))
5568 goto char_ok;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005569 }
5570
5571 if (expansion < 2
5572 && ( (all_digits && !isdigit(ch))
5573 || (!all_digits && !isalnum(ch) && ch != '_')
5574 )
5575 ) {
5576 /* handle parameter expansions
5577 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5578 */
5579 if (first_char)
5580 goto case_default;
5581 switch (ch) {
5582 case ':': /* null modifier */
5583 if (expansion == 0) {
5584 debug_printf_parse(": null modifier\n");
5585 ++expansion;
5586 break;
5587 }
5588 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005589 case '#': /* remove prefix */
5590 case '%': /* remove suffix */
5591 if (expansion == 0) {
5592 debug_printf_parse(": remove suffix/prefix\n");
5593 expansion = 2;
5594 break;
5595 }
5596 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005597 case '-': /* default value */
5598 case '=': /* assign default */
5599 case '+': /* alternative */
5600 case '?': /* error indicate */
5601 debug_printf_parse(": parameter expansion\n");
5602 expansion = 2;
5603 break;
5604 default:
5605 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005606 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005607 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5608 return 1;
5609 }
5610 }
5611 char_ok:
5612 debug_printf_parse(": '%c'\n", ch);
5613 o_addchr(dest, ch | quote_mask);
5614 quote_mask = 0;
5615 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005616 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005617 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5618 break;
5619 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005620#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005621 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005622# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005623 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005624# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005625 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005626 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005627# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005628 if (i_peek(input) == '(') {
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);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005631 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5632 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005633# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005634 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005635# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005636 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005637# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005638 if (as_string) {
5639 o_addstr(as_string, dest->data + pos);
5640 o_addchr(as_string, ')');
5641 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005642 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005643# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005644 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005645 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005646 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005647# endif
5648# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005649 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5650 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005651# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005652 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005653# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005654 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005655# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005656 if (as_string) {
5657 o_addstr(as_string, dest->data + pos);
5658 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005659 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005660# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005661 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005662# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005663 break;
5664 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005665#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005666 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005667 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005668 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005669 ch = i_peek(input);
5670 if (isalnum(ch)) { /* it's $_name or $_123 */
5671 ch = '_';
5672 goto make_var;
5673 }
5674 /* else: it's $_ */
5675 /* TODO: */
5676 /* $_ Shell or shell script name; or last cmd name */
5677 /* $- Option flags set by set builtin or shell options (-i etc) */
5678 default:
5679 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005680 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005681 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005682 return 0;
5683}
5684
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005685#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005686#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005687 parse_stream_dquoted(dest, input, dquote_end)
5688#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005689static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005690 o_string *dest,
5691 struct in_str *input,
5692 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005693{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005694 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005695 int next;
5696
5697 again:
5698 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005699 if (ch != EOF)
5700 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005701 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005702 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005703 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005704 debug_printf_parse("parse_stream_dquoted return 0\n");
5705 return 0;
5706 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005707 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005708 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005709 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005710 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005711 }
5712 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005713 if (ch != '\n') {
5714 next = i_peek(input);
5715 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005716 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5717 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005718 if (ch == '\\') {
5719 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005720 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005721 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005722 }
5723 /* bash:
5724 * "The backslash retains its special meaning [in "..."]
5725 * only when followed by one of the following characters:
5726 * $, `, ", \, or <newline>. A double quote may be quoted
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02005727 * within double quotes by preceding it with a backslash."
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005728 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005729 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005730 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005731 if (ch != '\n') {
5732 o_addqchr(dest, ch);
5733 nommu_addchr(as_string, ch);
5734 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005735 } else {
5736 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005737 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005738 }
5739 goto again;
5740 }
5741 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005742 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005743 debug_printf_parse("parse_stream_dquoted return 1: "
5744 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005745 return 1;
5746 }
5747 goto again;
5748 }
5749#if ENABLE_HUSH_TICK
5750 if (ch == '`') {
5751 //int pos = dest->length;
5752 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5753 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005754 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005755 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5756 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005757 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005758 }
5759#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005760 o_addQchr(dest, ch);
5761 if (ch == '='
5762 && (dest->o_assignment == MAYBE_ASSIGNMENT
5763 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005764 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005765 ) {
5766 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5767 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005768 goto again;
5769}
5770
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005771/*
5772 * Scan input until EOF or end_trigger char.
5773 * Return a list of pipes to execute, or NULL on EOF
5774 * or if end_trigger character is met.
5775 * On syntax error, exit is shell is not interactive,
5776 * reset parsing machinery and start parsing anew,
5777 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005778 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005779static struct pipe *parse_stream(char **pstring,
5780 struct in_str *input,
5781 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005782{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005783 struct parse_context ctx;
5784 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005785 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005786 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005787
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005788 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005789 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005790 * found. When recursing, quote state is passed in via dest->o_escape.
5791 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005792 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
Denys Vlasenko90a99042009-09-06 02:36:23 +02005793 end_trigger ? end_trigger : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005794 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005795
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005796 G.ifs = get_local_var_value("IFS");
5797 if (G.ifs == NULL)
5798 G.ifs = " \t\n";
5799
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005800 reset:
5801#if ENABLE_HUSH_INTERACTIVE
5802 input->promptmode = 0; /* PS1 */
5803#endif
5804 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5805 initialize_context(&ctx);
5806 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005807 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005808 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005809 const char *is_ifs;
5810 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005811 int ch;
5812 int next;
5813 int redir_fd;
5814 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005815
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005816 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005817 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005818 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005819 goto parse_error;
5820 }
5821 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005822 is_in_dquote = 0;
5823 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005824 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005825 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5826 ch, ch, dest.o_escape);
5827 if (ch == EOF) {
5828 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005829
5830 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005831 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005832 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005833 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005834 /* end_trigger == '}' case errors out earlier,
5835 * checking only ')' */
5836 if (end_trigger == ')') {
5837 syntax_error_unterm_ch('('); /* exits */
5838 /* goto parse_error; */
5839 }
5840
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005841 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005842 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005843 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005844 o_free(&dest);
5845 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005846 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005847 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005848 /* (this makes bare "&" cmd a no-op.
5849 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005850 if (pi->num_cmds == 0
5851 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5852 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005853 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005854 pi = NULL;
5855 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005856#if !BB_MMU
5857 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5858 if (pstring)
5859 *pstring = ctx.as_string.data;
5860 else
5861 o_free_unsafe(&ctx.as_string);
5862#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005863 debug_leave();
5864 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005865 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005866 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005867 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005868 is_ifs = strchr(G.ifs, ch);
5869 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005870 "\\$\"" IF_HUSH_TICK("`") /* always special */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005871 , ch);
5872
5873 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005874 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005875 o_addQchr(&dest, ch);
5876 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5877 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005878 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005879 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005880 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005881 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005882 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005883 continue;
5884 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005885
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005886 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005887 if (done_word(&dest, &ctx)) {
5888 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005889 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005890 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005891#if ENABLE_HUSH_CASE
5892 /* "case ... in <newline> word) ..." -
5893 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005894 if (ctx.command->argv == NULL
5895 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005896 ) {
5897 continue;
5898 }
5899#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005900 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005901 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005902 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5903 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005904 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005905 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005906 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005907 heredoc_cnt = 0;
5908 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005909 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005910 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005911 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005912 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005913 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005914 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005915
5916 /* "cmd}" or "cmd }..." without semicolon or &:
5917 * } is an ordinary char in this case, even inside { cmd; }
5918 * Pathological example: { ""}; } should exec "}" cmd
5919 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005920 if (ch == '}') {
5921 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5922 || dest.length != 0 /* word} */
5923 || dest.o_quoted /* ""} */
5924 ) {
5925 goto ordinary_char;
5926 }
5927 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5928 goto skip_end_trigger;
5929 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005930 }
5931
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005932 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005933 && (ch != ';' || heredoc_cnt == 0)
5934#if ENABLE_HUSH_CASE
5935 && (ch != ')'
5936 || ctx.ctx_res_w != RES_MATCH
5937 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5938 )
5939#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005940 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005941 if (heredoc_cnt) {
5942 /* This is technically valid:
5943 * { cat <<HERE; }; echo Ok
5944 * heredoc
5945 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005946 * HERE
5947 * but we don't support this.
5948 * We require heredoc to be in enclosing {}/(),
5949 * if any.
5950 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005951 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005952 goto parse_error;
5953 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005954 if (done_word(&dest, &ctx)) {
5955 goto parse_error;
5956 }
5957 done_pipe(&ctx, PIPE_SEQ);
5958 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005959 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005960 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005961 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005962 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005963 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005964#if !BB_MMU
5965 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5966 if (pstring)
5967 *pstring = ctx.as_string.data;
5968 else
5969 o_free_unsafe(&ctx.as_string);
5970#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005971 debug_leave();
5972 debug_printf_parse("parse_stream return %p: "
5973 "end_trigger char found\n",
5974 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005975 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005976 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005977 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005978 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005979 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005980 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005981
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005982 next = '\0';
5983 if (ch != '\n') {
5984 next = i_peek(input);
5985 }
5986
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005987 /* Catch <, > before deciding whether this word is
5988 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5989 switch (ch) {
5990 case '>':
5991 redir_fd = redirect_opt_num(&dest);
5992 if (done_word(&dest, &ctx)) {
5993 goto parse_error;
5994 }
5995 redir_style = REDIRECT_OVERWRITE;
5996 if (next == '>') {
5997 redir_style = REDIRECT_APPEND;
5998 ch = i_getch(input);
5999 nommu_addchr(&ctx.as_string, ch);
6000 }
6001#if 0
6002 else if (next == '(') {
6003 syntax_error(">(process) not supported");
6004 goto parse_error;
6005 }
6006#endif
6007 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6008 goto parse_error;
6009 continue; /* back to top of while (1) */
6010 case '<':
6011 redir_fd = redirect_opt_num(&dest);
6012 if (done_word(&dest, &ctx)) {
6013 goto parse_error;
6014 }
6015 redir_style = REDIRECT_INPUT;
6016 if (next == '<') {
6017 redir_style = REDIRECT_HEREDOC;
6018 heredoc_cnt++;
6019 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
6020 ch = i_getch(input);
6021 nommu_addchr(&ctx.as_string, ch);
6022 } else if (next == '>') {
6023 redir_style = REDIRECT_IO;
6024 ch = i_getch(input);
6025 nommu_addchr(&ctx.as_string, ch);
6026 }
6027#if 0
6028 else if (next == '(') {
6029 syntax_error("<(process) not supported");
6030 goto parse_error;
6031 }
6032#endif
6033 if (parse_redirect(&ctx, redir_fd, redir_style, input))
6034 goto parse_error;
6035 continue; /* back to top of while (1) */
6036 }
6037
6038 if (dest.o_assignment == MAYBE_ASSIGNMENT
6039 /* check that we are not in word in "a=1 2>word b=1": */
6040 && !ctx.pending_redirect
6041 ) {
6042 /* ch is a special char and thus this word
6043 * cannot be an assignment */
6044 dest.o_assignment = NOT_ASSIGNMENT;
6045 }
6046
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006047 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
6048
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006049 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00006050 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006051 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006052 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006053 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006054 if (ch == EOF || ch == '\n')
6055 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006056 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006057 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006058 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006059 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00006060 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006061 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006062 }
6063 break;
6064 case '\\':
6065 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006066 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006067 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00006068 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006069 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006070 if (ch != '\n') {
6071 o_addchr(&dest, '\\');
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006072 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006073 o_addchr(&dest, ch);
6074 nommu_addchr(&ctx.as_string, ch);
6075 /* Example: echo Hello \2>file
6076 * we need to know that word 2 is quoted */
6077 dest.o_quoted = 1;
Denys Vlasenkocbfe6ad2009-08-12 19:47:44 +02006078 } else {
6079#if !BB_MMU
6080 /* It's "\<newline>". Remove trailing '\' from ctx.as_string */
6081 ctx.as_string.data[--ctx.as_string.length] = '\0';
6082#endif
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02006083 }
Eric Andersen25f27032001-04-26 23:22:31 +00006084 break;
6085 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006086 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00006087 debug_printf_parse("parse_stream parse error: "
6088 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006089 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006090 }
Eric Andersen25f27032001-04-26 23:22:31 +00006091 break;
6092 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006093 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006094 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00006095 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006096 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00006097 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006098 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006099 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006100 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006101 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00006102 break;
Denys Vlasenkoe640cb42009-05-28 16:49:11 +02006103 o_addqchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006104 }
Eric Andersen25f27032001-04-26 23:22:31 +00006105 break;
6106 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006107 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00006108 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006109 if (dest.o_assignment == NOT_ASSIGNMENT)
6110 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00006111 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006112#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006113 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006114#if !BB_MMU
6115 int pos;
6116#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006117 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6118 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006119#if !BB_MMU
6120 pos = dest.length;
6121#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006122 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00006123#if !BB_MMU
6124 o_addstr(&ctx.as_string, dest.data + pos);
6125 o_addchr(&ctx.as_string, '`');
6126#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006127 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
6128 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00006129 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00006130 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00006131#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006132 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006133#if ENABLE_HUSH_CASE
6134 case_semi:
6135#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006136 if (done_word(&dest, &ctx)) {
6137 goto parse_error;
6138 }
6139 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006140#if ENABLE_HUSH_CASE
6141 /* Eat multiple semicolons, detect
6142 * whether it means something special */
6143 while (1) {
6144 ch = i_peek(input);
6145 if (ch != ';')
6146 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006147 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006148 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02006149 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006150 ctx.ctx_dsemicolon = 1;
6151 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006152 break;
6153 }
6154 }
6155#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006156 new_cmd:
6157 /* We just finished a cmd. New one may start
6158 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006159 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00006160 break;
6161 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006162 if (done_word(&dest, &ctx)) {
6163 goto parse_error;
6164 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00006165 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006166 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006167 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006168 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00006169 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006170 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00006171 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006172 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006173 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006174 if (done_word(&dest, &ctx)) {
6175 goto parse_error;
6176 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006177#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006178 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00006179 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00006180#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006181 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00006182 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006183 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006184 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00006185 } else {
6186 /* we could pick up a file descriptor choice here
6187 * with redirect_opt_num(), but bash doesn't do it.
6188 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006189 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00006190 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006191 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006192 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006193#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00006194 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006195 if (ctx.ctx_res_w == RES_MATCH
6196 && ctx.command->argv == NULL /* not (word|(... */
6197 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00006198 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006199 ) {
6200 continue;
6201 }
6202#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006203 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006204 if (parse_group(&dest, &ctx, input, ch) != 0) {
6205 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00006206 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00006207 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00006208 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006209#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006210 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00006211 goto case_semi;
6212#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006213 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00006214 /* proper use of this character is caught by end_trigger:
6215 * if we see {, we call parse_group(..., end_trigger='}')
6216 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00006217 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006218 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00006219 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00006220 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00006221 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00006222 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006223 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006224
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006225 parse_error:
6226 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006227 struct parse_context *pctx;
6228 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006229
6230 /* Clean up allocated tree.
Denys Vlasenko764b2f02009-06-07 16:05:04 +02006231 * Sample for finding leaks on syntax error recovery path.
6232 * Run it from interactive shell, watch pmap `pidof hush`.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006233 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00006234 * Samples to catch leaks at execution:
6235 * while if (true | {true;}); then echo ok; fi; do break; done
6236 * 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 +00006237 */
6238 pctx = &ctx;
6239 do {
6240 /* Update pipe/command counts,
6241 * otherwise freeing may miss some */
6242 done_pipe(pctx, PIPE_SEQ);
6243 debug_printf_clean("freeing list %p from ctx %p\n",
6244 pctx->list_head, pctx);
6245 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006246 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006247 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006248#if !BB_MMU
6249 o_free_unsafe(&pctx->as_string);
6250#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006251 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006252 if (pctx != &ctx) {
6253 free(pctx);
6254 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006255 IF_HAS_KEYWORDS(pctx = p2;)
6256 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006257 /* Free text, clear all dest fields */
6258 o_free(&dest);
6259 /* If we are not in top-level parse, we return,
6260 * our caller will propagate error.
6261 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006262 if (end_trigger != ';') {
6263#if !BB_MMU
6264 if (pstring)
6265 *pstring = NULL;
6266#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00006267 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006268 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006269 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006270 /* Discard cached input, force prompt */
6271 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006272 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006273 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00006274 }
Eric Andersen25f27032001-04-26 23:22:31 +00006275}
6276
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006277/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006278 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
6279 * end_trigger controls how often we stop parsing
6280 * NUL: parse all, execute, return
6281 * ';': parse till ';' or newline, execute, repeat till EOF
6282 */
6283static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00006284{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006285 while (1) {
6286 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00006287
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00006288 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006289 if (!pipe_list) /* EOF */
6290 break;
6291 debug_print_tree(pipe_list, 0);
6292 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
6293 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006294 }
Eric Andersen25f27032001-04-26 23:22:31 +00006295}
6296
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006297static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00006298{
6299 struct in_str input;
6300 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006301 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00006302}
6303
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006304static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006305{
Eric Andersen25f27032001-04-26 23:22:31 +00006306 struct in_str input;
6307 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006308 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006309}
6310
Denis Vlasenkof9375282009-04-05 19:13:39 +00006311/* Called a few times only (or even once if "sh -c") */
6312static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006313{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006314 unsigned sig;
6315 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006316
Denis Vlasenkof9375282009-04-05 19:13:39 +00006317 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006318 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006319 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006320 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006321 mask |= SPECIAL_JOB_SIGS;
6322 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006323 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006324
Denis Vlasenkof9375282009-04-05 19:13:39 +00006325 if (!second_time)
6326 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6327 sig = 0;
6328 while (mask) {
6329 if (mask & 1)
6330 sigaddset(&G.blocked_set, sig);
6331 mask >>= 1;
6332 sig++;
6333 }
6334 sigdelset(&G.blocked_set, SIGCHLD);
6335
6336 sigprocmask(SIG_SETMASK, &G.blocked_set,
6337 second_time ? NULL : &G.inherited_set);
6338 /* POSIX allows shell to re-enable SIGCHLD
6339 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006340#if ENABLE_HUSH_FAST
6341 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006342 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006343 signal(SIGCHLD, SIGCHLD_handler);
6344#else
6345 if (!second_time)
6346 signal(SIGCHLD, SIG_DFL);
6347#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006348}
6349
6350#if ENABLE_HUSH_JOB
6351/* helper */
6352static void maybe_set_to_sigexit(int sig)
6353{
6354 void (*handler)(int);
6355 /* non_DFL_mask'ed signals are, well, masked,
6356 * no need to set handler for them.
6357 */
6358 if (!((G.non_DFL_mask >> sig) & 1)) {
6359 handler = signal(sig, sigexit);
6360 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6361 signal(sig, handler);
6362 }
6363}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006364/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006365static void set_fatal_handlers(void)
6366{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006367 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006368 if (HUSH_DEBUG) {
6369 maybe_set_to_sigexit(SIGILL );
6370 maybe_set_to_sigexit(SIGFPE );
6371 maybe_set_to_sigexit(SIGBUS );
6372 maybe_set_to_sigexit(SIGSEGV);
6373 maybe_set_to_sigexit(SIGTRAP);
6374 } /* else: hush is perfect. what SEGV? */
6375 maybe_set_to_sigexit(SIGABRT);
6376 /* bash 3.2 seems to handle these just like 'fatal' ones */
6377 maybe_set_to_sigexit(SIGPIPE);
6378 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006379 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006380 * if we aren't interactive... but in this case
6381 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006382 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006383 /*maybe_set_to_sigexit(SIGTERM);*/
6384 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006385}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006386#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006387
Denis Vlasenkod5762932009-03-31 11:22:57 +00006388static int set_mode(const char cstate, const char mode)
6389{
6390 int state = (cstate == '-' ? 1 : 0);
6391 switch (mode) {
6392 case 'n': G.fake_mode = state; break;
6393 case 'x': /*G.debug_mode = state;*/ break;
6394 default: return EXIT_FAILURE;
6395 }
6396 return EXIT_SUCCESS;
6397}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006398
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006399int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006400int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006401{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006402 static const struct variable const_shell_ver = {
6403 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006404 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006405 .max_len = 1, /* 0 can provoke free(name) */
6406 .flg_export = 1,
6407 .flg_read_only = 1,
6408 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006409 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006410 int opt;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006411 unsigned builtin_argc;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006412 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006413 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006414
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006415 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006416 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006417 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006418#if !BB_MMU
6419 G.argv0_for_re_execing = argv[0];
6420#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006421 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006422 G.shell_ver = const_shell_ver; /* copying struct here */
6423 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006424 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006425 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6426 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006427 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006428 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006429 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006430 if (e) while (*e) {
6431 char *value = strchr(*e, '=');
6432 if (value) { /* paranoia */
6433 cur_var->next = xzalloc(sizeof(*cur_var));
6434 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006435 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006436 cur_var->max_len = strlen(*e);
6437 cur_var->flg_export = 1;
6438 }
6439 e++;
6440 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006441 /* reinstate HUSH_VERSION */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006442 debug_printf_env("putenv '%s'\n", hush_version_str);
Denys Vlasenko6db47842009-09-05 20:15:17 +02006443 putenv((char *)hush_version_str);
6444
6445 /* Export PWD */
6446 set_pwd_var(/*exp:*/ 1);
6447 /* bash also exports SHLVL and _,
6448 * and sets (but doesn't export) the following variables:
6449 * BASH=/bin/bash
6450 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
6451 * BASH_VERSION='3.2.0(1)-release'
6452 * HOSTTYPE=i386
6453 * MACHTYPE=i386-pc-linux-gnu
6454 * OSTYPE=linux-gnu
6455 * HOSTNAME=<xxxxxxxxxx>
6456 * PPID=<NNNNN>
6457 * EUID=<NNNNN>
6458 * UID=<NNNNN>
6459 * GROUPS=()
6460 * LINES=<NNN>
6461 * COLUMNS=<NNN>
6462 * BASH_ARGC=()
6463 * BASH_ARGV=()
6464 * BASH_LINENO=()
6465 * BASH_SOURCE=()
6466 * DIRSTACK=()
6467 * PIPESTATUS=([0]="0")
6468 * HISTFILE=/<xxx>/.bash_history
6469 * HISTFILESIZE=500
6470 * HISTSIZE=500
6471 * MAILCHECK=60
6472 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
6473 * SHELL=/bin/bash
6474 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
6475 * TERM=dumb
6476 * OPTERR=1
6477 * OPTIND=1
6478 * IFS=$' \t\n'
6479 * PS1='\s-\v\$ '
6480 * PS2='> '
6481 * PS4='+ '
6482 */
6483
Denis Vlasenko38f63192007-01-22 09:03:07 +00006484#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006485 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006486#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006487 G.global_argc = argc;
6488 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006489 /* Initialize some more globals to non-zero values */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006490 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006491
Denis Vlasenkoed782372009-04-10 00:45:02 +00006492 if (setjmp(die_jmp)) {
6493 /* xfunc has failed! die die die */
6494 /* no EXIT traps, this is an escape hatch! */
6495 G.exiting = 1;
6496 hush_exit(xfunc_error_retval);
6497 }
6498
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006499 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006500 * block_signals(0) if we are going to execute "sh <script>",
6501 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006502 * If we later decide that we are interactive, we run block_signals(0)
6503 * (or re-run block_signals(1) if we ran block_signals(0) before)
6504 * in order to intercept (more) signals.
6505 */
6506
6507 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006508 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006509 builtin_argc = 0;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006510 while (1) {
Denys Vlasenkoa67a9622009-08-20 03:38:58 +02006511 opt = getopt(argc, argv, "+c:xins"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006512#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006513 "<:$:R:V:"
6514# if ENABLE_HUSH_FUNCTIONS
6515 "F:"
6516# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006517#endif
6518 );
6519 if (opt <= 0)
6520 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006521 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006522 case 'c':
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006523 /* Possibilities:
6524 * sh ... -c 'script'
6525 * sh ... -c 'script' ARG0 [ARG1...]
6526 * On NOMMU, if builtin_argc != 0,
6527 * sh ... -c 'builtin' [BARGV...] "" ARG0 [ARG1...]
6528 * "" needs to be replaced with NULL
6529 * and BARGV vector fed to builtin function.
6530 * Note: this form never happens:
6531 * sh ... -c 'builtin' [BARGV...] ""
6532 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006533 if (!G.root_pid)
6534 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00006535 G.global_argv = argv + optind;
6536 G.global_argc = argc - optind;
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006537 if (builtin_argc) {
6538 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
6539 const struct built_in_command *x;
6540
6541 block_signals(0); /* 0: called 1st time */
6542 x = find_builtin(optarg);
6543 if (x) { /* paranoia */
6544 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
6545 G.global_argv += builtin_argc;
6546 G.global_argv[-1] = NULL; /* replace "" */
6547 G.last_exitcode = x->function(argv + optind - 1);
6548 }
6549 goto final_return;
6550 }
6551 if (!G.global_argv[0]) {
6552 /* -c 'script' (no params): prevent empty $0 */
6553 G.global_argv--; /* points to argv[i] of 'script' */
6554 G.global_argv[0] = argv[0];
6555 G.global_argc--;
6556 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006557 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006558 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006559 goto final_return;
6560 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006561 /* Well, we cannot just declare interactiveness,
6562 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006563 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006564 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006565 case 's':
6566 /* "-s" means "read from stdin", but this is how we always
6567 * operate, so simply do nothing here. */
6568 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006569#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006570 case '<': /* "big heredoc" support */
6571 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6572 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006573 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006574 G.root_pid = bb_strtou(optarg, &optarg, 16);
6575 optarg++;
6576 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6577 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006578 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006579 optarg++;
6580 builtin_argc = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006581# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006582 optarg++;
6583 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006584# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006585 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006586 case 'R':
6587 case 'V':
Denys Vlasenko295fef82009-06-03 12:47:26 +02006588 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006589 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006590# if ENABLE_HUSH_FUNCTIONS
6591 case 'F': {
6592 struct function *funcp = new_function(optarg);
6593 /* funcp->name is already set to optarg */
6594 /* funcp->body is set to NULL. It's a special case. */
6595 funcp->body_as_string = argv[optind];
6596 optind++;
6597 break;
6598 }
6599# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006600#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006601 case 'n':
6602 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006603 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006604 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006605 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006606#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006607 fprintf(stderr, "Usage: sh [FILE]...\n"
6608 " or: sh -c command [args]...\n\n");
6609 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006610#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006611 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006612#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006613 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006614 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006615
6616 if (!G.root_pid)
6617 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00006618
6619 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006620 if (argv[0] && argv[0][0] == '-') {
6621 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006622 debug_printf("sourcing /etc/profile\n");
6623 input = fopen_for_read("/etc/profile");
6624 if (input != NULL) {
6625 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006626 block_signals(0); /* 0: called 1st time */
6627 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006628 parse_and_run_file(input);
6629 fclose(input);
6630 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006631 /* bash: after sourcing /etc/profile,
6632 * tries to source (in the given order):
6633 * ~/.bash_profile, ~/.bash_login, ~/.profile,
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006634 * stopping on first found. --noprofile turns this off.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006635 * bash also sources ~/.bash_logout on exit.
6636 * If called as sh, skips .bash_XXX files.
6637 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006638 }
6639
Denis Vlasenkof9375282009-04-05 19:13:39 +00006640 if (argv[optind]) {
6641 FILE *input;
6642 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006643 * "bash <script>" (which is never interactive (unless -i?))
6644 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006645 * If called as sh, does the same but with $ENV.
6646 */
6647 debug_printf("running script '%s'\n", argv[optind]);
6648 G.global_argv = argv + optind;
6649 G.global_argc = argc - optind;
6650 input = xfopen_for_read(argv[optind]);
6651 close_on_exec_on(fileno(input));
6652 if (!signal_mask_is_inited)
6653 block_signals(0); /* 0: called 1st time */
6654 parse_and_run_file(input);
6655#if ENABLE_FEATURE_CLEAN_UP
6656 fclose(input);
6657#endif
6658 goto final_return;
6659 }
6660
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006661 /* Up to here, shell was non-interactive. Now it may become one.
6662 * NB: don't forget to (re)run block_signals(0/1) as needed.
6663 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006664
Denys Vlasenko28a105d2009-06-01 11:26:30 +02006665 /* A shell is interactive if the '-i' flag was given,
6666 * or if all of the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006667 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006668 * no arguments remaining or the -s flag given
6669 * standard input is a terminal
6670 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006671 * Refer to Posix.2, the description of the 'sh' utility.
6672 */
6673#if ENABLE_HUSH_JOB
6674 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04006675 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6676 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6677 if (G_saved_tty_pgrp < 0)
6678 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006679
6680 /* try to dup stdin to high fd#, >= 255 */
6681 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6682 if (G_interactive_fd < 0) {
6683 /* try to dup to any fd */
6684 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006685 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006686 /* give up */
6687 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04006688 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006689 }
6690 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006691// TODO: track & disallow any attempts of user
6692// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006693 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006694 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006695 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006696 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006697
Mike Frysinger38478a62009-05-20 04:48:06 -04006698 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006699 /* If we were run as 'hush &', sleep until we are
6700 * in the foreground (tty pgrp == our pgrp).
6701 * If we get started under a job aware app (like bash),
6702 * make sure we are now in charge so we don't fight over
6703 * who gets the foreground */
6704 while (1) {
6705 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04006706 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6707 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006708 break;
6709 /* send TTIN to ourself (should stop us) */
6710 kill(- shell_pgrp, SIGTTIN);
6711 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006712 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006713
Denis Vlasenkof9375282009-04-05 19:13:39 +00006714 /* Block some signals */
6715 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006716
Mike Frysinger38478a62009-05-20 04:48:06 -04006717 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006718 /* Set other signals to restore saved_tty_pgrp */
6719 set_fatal_handlers();
6720 /* Put ourselves in our own process group
6721 * (bash, too, does this only if ctty is available) */
6722 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6723 /* Grab control of the terminal */
6724 tcsetpgrp(G_interactive_fd, getpid());
6725 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006726 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006727 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006728 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006729 } else if (!signal_mask_is_inited) {
6730 block_signals(0); /* 0: called 1st time */
6731 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006732#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006733 /* No job control compiled in, only prompt/line editing */
6734 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006735 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6736 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006737 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006738 G_interactive_fd = dup(STDIN_FILENO);
6739 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006740 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006741 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006742 }
6743 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006744 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006745 close_on_exec_on(G_interactive_fd);
6746 block_signals(signal_mask_is_inited);
6747 } else if (!signal_mask_is_inited) {
6748 block_signals(0);
6749 }
6750#else
6751 /* We have interactiveness code disabled */
6752 if (!signal_mask_is_inited) {
6753 block_signals(0);
6754 }
6755#endif
6756 /* bash:
6757 * if interactive but not a login shell, sources ~/.bashrc
6758 * (--norc turns this off, --rcfile <file> overrides)
6759 */
6760
6761 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006762 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysinger26cf2832009-04-24 06:40:30 +00006763 if (ENABLE_HUSH_HELP)
6764 puts("Enter 'help' for a list of built-in commands.");
6765 puts("");
Mike Frysingerb2705e12009-03-23 08:44:02 +00006766 }
6767
Denis Vlasenkof9375282009-04-05 19:13:39 +00006768 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006769
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006770 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006771#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006772 if (G.cwd != bb_msg_unknown)
6773 free((char*)G.cwd);
6774 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006775 while (cur_var) {
6776 struct variable *tmp = cur_var;
6777 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006778 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006779 cur_var = cur_var->next;
6780 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006781 }
Eric Andersen25f27032001-04-26 23:22:31 +00006782#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006783 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006784}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006785
6786
6787#if ENABLE_LASH
6788int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6789int lash_main(int argc, char **argv)
6790{
Denys Vlasenko07934912009-08-20 03:40:04 +02006791 bb_error_msg("lash is deprecated, please use hush instead");
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006792 return hush_main(argc, argv);
6793}
6794#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006795
Denys Vlasenko1cc4b132009-08-21 00:05:51 +02006796#if ENABLE_MSH
6797int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6798int msh_main(int argc, char **argv)
6799{
6800 //bb_error_msg("msh is deprecated, please use hush instead");
6801 return hush_main(argc, argv);
6802}
6803#endif
6804
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006805
6806/*
6807 * Built-ins
6808 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006809static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006810{
6811 return 0;
6812}
6813
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006814static int FAST_FUNC builtin_test(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006815{
6816 int argc = 0;
6817 while (*argv) {
6818 argc++;
6819 argv++;
6820 }
6821 return test_main(argc, argv - argc);
6822}
6823
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006824static int FAST_FUNC builtin_echo(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006825{
6826 int argc = 0;
6827 while (*argv) {
6828 argc++;
6829 argv++;
6830 }
6831 return echo_main(argc, argv - argc);
6832}
6833
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006834static int FAST_FUNC builtin_eval(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006835{
6836 int rcode = EXIT_SUCCESS;
6837
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006838 if (*++argv) {
6839 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006840 /* bash:
6841 * eval "echo Hi; done" ("done" is syntax error):
6842 * "echo Hi" will not execute too.
6843 */
6844 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006845 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006846 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006847 }
6848 return rcode;
6849}
6850
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006851static int FAST_FUNC builtin_cd(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006852{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006853 const char *newdir = argv[1];
6854 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006855 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006856 * bash says "bash: cd: HOME not set" and does nothing
6857 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006858 */
Denys Vlasenko90a99042009-09-06 02:36:23 +02006859 const char *home = get_local_var_value("HOME");
6860 newdir = home ? home : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006861 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006862 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006863 /* Mimic bash message exactly */
6864 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006865 return EXIT_FAILURE;
6866 }
Denys Vlasenko6db47842009-09-05 20:15:17 +02006867 /* Read current dir (get_cwd(1) is inside) and set PWD.
6868 * Note: do not enforce exporting. If PWD was unset or unexported,
6869 * set it again, but do not export. bash does the same.
6870 */
6871 set_pwd_var(/*exp:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006872 return EXIT_SUCCESS;
6873}
6874
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006875static int FAST_FUNC builtin_exec(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006876{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006877 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006878 return EXIT_SUCCESS; /* bash does this */
6879 {
6880#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006881 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006882#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006883 /* TODO: if exec fails, bash does NOT exit! We do... */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006884 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006885 /* never returns */
6886 }
6887}
6888
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006889static int FAST_FUNC builtin_exit(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006890{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006891 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00006892
6893 /* interactive bash:
6894 * # trap "echo EEE" EXIT
6895 * # exit
6896 * exit
6897 * There are stopped jobs.
6898 * (if there are _stopped_ jobs, running ones don't count)
6899 * # exit
6900 * exit
6901 # EEE (then bash exits)
6902 *
6903 * we can use G.exiting = -1 as indicator "last cmd was exit"
6904 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006905
6906 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006907 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006908 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006909 /* mimic bash: exit 123abc == exit 255 + error msg */
6910 xfunc_error_retval = 255;
6911 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006912 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006913}
6914
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006915static void print_escaped(const char *s)
6916{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006917 if (*s == '\'')
6918 goto squote;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006919 do {
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02006920 const char *p = strchrnul(s, '\'');
6921 /* print 'xxxx', possibly just '' */
6922 printf("'%.*s'", (int)(p - s), s);
6923 if (*p == '\0')
6924 break;
6925 s = p;
6926 squote:
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006927 /* s points to '; print "'''...'''" */
6928 putchar('"');
6929 do putchar('\''); while (*++s == '\'');
6930 putchar('"');
6931 } while (*s);
6932}
6933
Denys Vlasenko295fef82009-06-03 12:47:26 +02006934#if !ENABLE_HUSH_LOCAL
6935#define helper_export_local(argv, exp, lvl) \
6936 helper_export_local(argv, exp)
6937#endif
6938static void helper_export_local(char **argv, int exp, int lvl)
6939{
6940 do {
6941 char *name = *argv;
6942
6943 /* So far we do not check that name is valid (TODO?) */
6944
6945 if (strchr(name, '=') == NULL) {
6946 struct variable *var;
6947
6948 var = get_local_var(name);
6949 if (exp == -1) { /* unexporting? */
6950 /* export -n NAME (without =VALUE) */
6951 if (var) {
6952 var->flg_export = 0;
6953 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6954 unsetenv(name);
6955 } /* else: export -n NOT_EXISTING_VAR: no-op */
6956 continue;
6957 }
6958 if (exp == 1) { /* exporting? */
6959 /* export NAME (without =VALUE) */
6960 if (var) {
6961 var->flg_export = 1;
6962 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6963 putenv(var->varstr);
6964 continue;
6965 }
6966 }
6967 /* Exporting non-existing variable.
6968 * bash does not put it in environment,
6969 * but remembers that it is exported,
6970 * and does put it in env when it is set later.
6971 * We just set it to "" and export. */
6972 /* Or, it's "local NAME" (without =VALUE).
6973 * bash sets the value to "". */
6974 name = xasprintf("%s=", name);
6975 } else {
6976 /* (Un)exporting/making local NAME=VALUE */
6977 name = xstrdup(name);
6978 }
6979 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
6980 } while (*++argv);
6981}
6982
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02006983static int FAST_FUNC builtin_export(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006984{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006985 unsigned opt_unexport;
6986
Denys Vlasenkodf5131c2009-06-07 16:04:17 +02006987#if ENABLE_HUSH_EXPORT_N
6988 /* "!": do not abort on errors */
6989 opt_unexport = getopt32(argv, "!n");
6990 if (opt_unexport == (uint32_t)-1)
6991 return EXIT_FAILURE;
6992 argv += optind;
6993#else
6994 opt_unexport = 0;
6995 argv++;
6996#endif
6997
6998 if (argv[0] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006999 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007000 if (e) {
7001 while (*e) {
7002#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007003 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007004#else
7005 /* ash emits: export VAR='VAL'
7006 * bash: declare -x VAR="VAL"
7007 * we follow ash example */
7008 const char *s = *e++;
7009 const char *p = strchr(s, '=');
7010
7011 if (!p) /* wtf? take next variable */
7012 continue;
7013 /* export var= */
7014 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007015 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007016 putchar('\n');
7017#endif
7018 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007019 /*fflush(stdout); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00007020 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007021 return EXIT_SUCCESS;
7022 }
7023
Denys Vlasenko295fef82009-06-03 12:47:26 +02007024 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007025
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007026 return EXIT_SUCCESS;
7027}
7028
Denys Vlasenko295fef82009-06-03 12:47:26 +02007029#if ENABLE_HUSH_LOCAL
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007030static int FAST_FUNC builtin_local(char **argv)
Denys Vlasenko295fef82009-06-03 12:47:26 +02007031{
7032 if (G.func_nest_level == 0) {
7033 bb_error_msg("%s: not in a function", argv[0]);
7034 return EXIT_FAILURE; /* bash compat */
7035 }
7036 helper_export_local(argv, 0, G.func_nest_level);
7037 return EXIT_SUCCESS;
7038}
7039#endif
7040
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007041static int FAST_FUNC builtin_trap(char **argv)
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007042{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007043 int sig;
7044 char *new_cmd;
7045
7046 if (!G.traps)
7047 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7048
7049 argv++;
7050 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007051 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007052 /* No args: print all trapped */
7053 for (i = 0; i < NSIG; ++i) {
7054 if (G.traps[i]) {
7055 printf("trap -- ");
7056 print_escaped(G.traps[i]);
7057 printf(" %s\n", get_signame(i));
7058 }
7059 }
7060 /*fflush(stdout); - done after each builtin anyway */
7061 return EXIT_SUCCESS;
7062 }
7063
7064 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007065 /* If first arg is a number: reset all specified signals */
7066 sig = bb_strtou(*argv, NULL, 10);
7067 if (errno == 0) {
7068 int ret;
7069 process_sig_list:
7070 ret = EXIT_SUCCESS;
7071 while (*argv) {
7072 sig = get_signum(*argv++);
7073 if (sig < 0 || sig >= NSIG) {
7074 ret = EXIT_FAILURE;
7075 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007076 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007077 continue;
7078 }
7079
7080 free(G.traps[sig]);
7081 G.traps[sig] = xstrdup(new_cmd);
7082
7083 debug_printf("trap: setting SIG%s (%i) to '%s'",
7084 get_signame(sig), sig, G.traps[sig]);
7085
7086 /* There is no signal for 0 (EXIT) */
7087 if (sig == 0)
7088 continue;
7089
7090 if (new_cmd) {
7091 sigaddset(&G.blocked_set, sig);
7092 } else {
7093 /* There was a trap handler, we are removing it
7094 * (if sig has non-DFL handling,
7095 * we don't need to do anything) */
7096 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
7097 continue;
7098 sigdelset(&G.blocked_set, sig);
7099 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007100 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00007101 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00007102 return ret;
7103 }
7104
7105 if (!argv[1]) { /* no second arg */
7106 bb_error_msg("trap: invalid arguments");
7107 return EXIT_FAILURE;
7108 }
7109
7110 /* First arg is "-": reset all specified to default */
7111 /* First arg is "--": skip it, the rest is "handler SIGs..." */
7112 /* Everything else: set arg as signal handler
7113 * (includes "" case, which ignores signal) */
7114 if (argv[0][0] == '-') {
7115 if (argv[0][1] == '\0') { /* "-" */
7116 /* new_cmd remains NULL: "reset these sigs" */
7117 goto reset_traps;
7118 }
7119 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
7120 argv++;
7121 }
7122 /* else: "-something", no special meaning */
7123 }
7124 new_cmd = *argv;
7125 reset_traps:
7126 argv++;
7127 goto process_sig_list;
7128}
7129
Mike Frysinger93cadc22009-05-27 17:06:25 -04007130/* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007131static int FAST_FUNC builtin_type(char **argv)
Mike Frysinger93cadc22009-05-27 17:06:25 -04007132{
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007133 int ret = EXIT_SUCCESS;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007134
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007135 while (*++argv) {
Mike Frysinger93cadc22009-05-27 17:06:25 -04007136 const char *type;
Denys Vlasenko171932d2009-05-28 17:07:22 +02007137 char *path = NULL;
Mike Frysinger93cadc22009-05-27 17:06:25 -04007138
7139 if (0) {} /* make conditional compile easier below */
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007140 /*else if (find_alias(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007141 type = "an alias";*/
7142#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007143 else if (find_function(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007144 type = "a function";
7145#endif
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007146 else if (find_builtin(*argv))
Mike Frysinger93cadc22009-05-27 17:06:25 -04007147 type = "a shell builtin";
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007148 else if ((path = find_in_path(*argv)) != NULL)
7149 type = path;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007150 else {
Denys Vlasenkodd6b2112009-05-28 09:45:50 +02007151 bb_error_msg("type: %s: not found", *argv);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007152 ret = EXIT_FAILURE;
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007153 continue;
7154 }
Mike Frysinger93cadc22009-05-27 17:06:25 -04007155
Denys Vlasenko5d7cca22009-05-28 09:58:43 +02007156 printf("%s is %s\n", *argv, type);
7157 free(path);
Mike Frysinger93cadc22009-05-27 17:06:25 -04007158 }
7159
7160 return ret;
7161}
7162
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007163#if ENABLE_HUSH_JOB
7164/* built-in 'fg' and 'bg' handler */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007165static int FAST_FUNC builtin_fg_bg(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007166{
7167 int i, jobnum;
7168 struct pipe *pi;
7169
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007170 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007171 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00007172
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007173 /* If they gave us no args, assume they want the last backgrounded task */
7174 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00007175 for (pi = G.job_list; pi; pi = pi->next) {
7176 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007177 goto found;
7178 }
7179 }
7180 bb_error_msg("%s: no current job", argv[0]);
7181 return EXIT_FAILURE;
7182 }
7183 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
7184 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
7185 return EXIT_FAILURE;
7186 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007187 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007188 if (pi->jobid == jobnum) {
7189 goto found;
7190 }
7191 }
7192 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
7193 return EXIT_FAILURE;
7194 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00007195 /* TODO: bash prints a string representation
7196 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04007197 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007198 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00007199 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007200 }
7201
7202 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007203 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
7204 for (i = 0; i < pi->num_cmds; i++) {
7205 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
7206 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007207 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007208 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007209
7210 i = kill(- pi->pgrp, SIGCONT);
7211 if (i < 0) {
7212 if (errno == ESRCH) {
7213 delete_finished_bg_job(pi);
7214 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007215 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007216 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007217 }
7218
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007219 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007220 remove_bg_job(pi);
7221 return checkjobs_and_fg_shell(pi);
7222 }
7223 return EXIT_SUCCESS;
7224}
7225#endif
7226
7227#if ENABLE_HUSH_HELP
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007228static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007229{
7230 const struct built_in_command *x;
7231
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007232 printf(
Denis Vlasenko34d4d892009-04-04 20:24:37 +00007233 "Built-in commands:\n"
7234 "------------------\n");
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007235 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
7236 if (x->descr)
7237 printf("%s\t%s\n", x->cmd, x->descr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007238 }
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007239 bb_putchar('\n');
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007240 return EXIT_SUCCESS;
7241}
7242#endif
7243
7244#if ENABLE_HUSH_JOB
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007245static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007246{
7247 struct pipe *job;
7248 const char *status_string;
7249
Denis Vlasenko87a86552008-07-29 19:43:10 +00007250 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00007251 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007252 status_string = "Stopped";
7253 else
7254 status_string = "Running";
7255
7256 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
7257 }
7258 return EXIT_SUCCESS;
7259}
7260#endif
7261
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007262#if HUSH_DEBUG
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007263static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007264{
7265 void *p;
7266 unsigned long l;
7267
7268 /* Crude attempt to find where "free memory" starts,
7269 * sans fragmentation. */
7270 p = malloc(240);
7271 l = (unsigned long)p;
7272 free(p);
7273 p = malloc(3400);
7274 if (l < (unsigned long)p) l = (unsigned long)p;
7275 free(p);
7276
7277 if (!G.memleak_value)
7278 G.memleak_value = l;
Denys Vlasenko9038d6f2009-07-15 20:02:19 +02007279
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00007280 l -= G.memleak_value;
7281 if ((long)l < 0)
7282 l = 0;
7283 l /= 1024;
7284 if (l > 127)
7285 l = 127;
7286
7287 /* Exitcode is "how many kilobytes we leaked since 1st call" */
7288 return l;
7289}
7290#endif
7291
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007292static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007293{
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +02007294 puts(get_cwd(0));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007295 return EXIT_SUCCESS;
7296}
7297
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007298static int FAST_FUNC builtin_read(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007299{
7300 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007301 const char *name = "REPLY";
7302
7303 if (argv[1]) {
7304 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007305 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
7306 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00007307 if (!is_well_formed_var_name(name, '\0')) {
7308 /* Mimic bash message */
7309 bb_error_msg("read: '%s': not a valid identifier", name);
7310 return 1;
7311 }
7312 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007313
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00007314//TODO: bash unbackslashes input, splits words and puts them in argv[i]
7315
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007316 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denys Vlasenko295fef82009-06-03 12:47:26 +02007317 return set_local_var(string, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007318}
7319
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007320/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
7321 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007322 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007323 * set [-abCefhmnuvx] [-o option] [argument...]
7324 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007325 * set -- [argument...]
7326 * set -o
7327 * set +o
7328 * Implementations shall support the options in both their hyphen and
7329 * plus-sign forms. These options can also be specified as options to sh.
7330 * Examples:
7331 * Write out all variables and their values: set
7332 * Set $1, $2, and $3 and set "$#" to 3: set c a b
7333 * Turn on the -x and -v options: set -xv
7334 * Unset all positional parameters: set --
7335 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
7336 * Set the positional parameters to the expansion of x, even if x expands
7337 * with a leading '-' or '+': set -- $x
7338 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007339 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007340 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007341static int FAST_FUNC builtin_set(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007342{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007343 int n;
7344 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007345 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007346
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007347 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007348 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007349 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007350 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007351 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00007352 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007353
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007354 do {
7355 if (!strcmp(arg, "--")) {
7356 ++argv;
7357 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007358 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00007359 if (arg[0] != '+' && arg[0] != '-')
7360 break;
7361 for (n = 1; arg[n]; ++n)
7362 if (set_mode(arg[0], arg[n]))
7363 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007364 } while ((arg = *++argv) != NULL);
7365 /* Now argv[0] is 1st argument */
7366
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007367 if (arg == NULL)
7368 return EXIT_SUCCESS;
7369 set_argv:
7370
Denis Vlasenko424f79b2009-03-22 14:23:34 +00007371 /* NB: G.global_argv[0] ($0) is never freed/changed */
7372 g_argv = G.global_argv;
7373 if (G.global_args_malloced) {
7374 pp = g_argv;
7375 while (*++pp)
7376 free(*pp);
7377 g_argv[1] = NULL;
7378 } else {
7379 G.global_args_malloced = 1;
7380 pp = xzalloc(sizeof(pp[0]) * 2);
7381 pp[0] = g_argv[0]; /* retain $0 */
7382 g_argv = pp;
7383 }
7384 /* This realloc's G.global_argv */
7385 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
7386
7387 n = 1;
7388 while (*++pp)
7389 n++;
7390 G.global_argc = n;
7391
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007392 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00007393
7394 /* Nothing known, so abort */
7395 error:
7396 bb_error_msg("set: %s: invalid option", arg);
7397 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007398}
7399
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007400static int FAST_FUNC builtin_shift(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007401{
7402 int n = 1;
7403 if (argv[1]) {
7404 n = atoi(argv[1]);
7405 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007406 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007407 if (G.global_args_malloced) {
7408 int m = 1;
7409 while (m <= n)
7410 free(G.global_argv[m++]);
7411 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007412 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00007413 memmove(&G.global_argv[1], &G.global_argv[n+1],
7414 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007415 return EXIT_SUCCESS;
7416 }
7417 return EXIT_FAILURE;
7418}
7419
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007420static int FAST_FUNC builtin_source(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007421{
Mike Frysinger93cadc22009-05-27 17:06:25 -04007422 char *arg_path;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007423 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007424 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007425#if ENABLE_HUSH_FUNCTIONS
7426 smallint sv_flg;
7427#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007428
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007429 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007430 return EXIT_FAILURE;
7431
Mike Frysinger93cadc22009-05-27 17:06:25 -04007432 if (strchr(*argv, '/') == NULL && (arg_path = find_in_path(*argv)) != NULL) {
7433 input = fopen_for_read(arg_path);
7434 free(arg_path);
7435 } else
7436 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007437 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007438 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007439 return EXIT_FAILURE;
7440 }
7441 close_on_exec_on(fileno(input));
7442
Mike Frysinger885b6f22009-04-18 21:04:25 +00007443#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007444 sv_flg = G.flag_return_in_progress;
7445 /* "we are inside sourced file, ok to use return" */
7446 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007447#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007448 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007449
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007450 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007451 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007452
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007453 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007454#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007455 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007456#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007457
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007458 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007459}
7460
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007461static int FAST_FUNC builtin_umask(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007462{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007463 int rc;
7464 mode_t mask;
7465
7466 mask = umask(0);
7467 if (argv[1]) {
7468 mode_t old_mask = mask;
7469
7470 mask ^= 0777;
7471 rc = bb_parse_mode(argv[1], &mask);
7472 mask ^= 0777;
7473 if (rc == 0) {
7474 mask = old_mask;
7475 /* bash messages:
7476 * bash: umask: 'q': invalid symbolic mode operator
7477 * bash: umask: 999: octal number out of range
7478 */
7479 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007480 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007481 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007482 rc = 1;
7483 /* Mimic bash */
7484 printf("%04o\n", (unsigned) mask);
7485 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007486 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007487 umask(mask);
7488
7489 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007490}
7491
Mike Frysingerd690f682009-03-30 06:50:54 +00007492/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007493static int FAST_FUNC builtin_unset(char **argv)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007494{
Mike Frysingerd690f682009-03-30 06:50:54 +00007495 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007496 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007497
Denis Vlasenko28e67962009-04-26 23:22:40 +00007498 /* "!": do not abort on errors */
7499 /* "+": stop at 1st non-option */
7500 opts = getopt32(argv, "!+vf");
7501 if (opts == (unsigned)-1)
7502 return EXIT_FAILURE;
7503 if (opts == 3) {
7504 bb_error_msg("unset: -v and -f are exclusive");
7505 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007506 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007507 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007508
7509 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007510 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007511 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007512 if (unset_local_var(*argv)) {
7513 /* unset <nonexistent_var> doesn't fail.
7514 * Error is when one tries to unset RO var.
7515 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007516 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007517 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007518 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007519#if ENABLE_HUSH_FUNCTIONS
7520 else {
7521 unset_func(*argv);
7522 }
7523#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007524 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007525 }
7526 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007527}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007528
Mike Frysinger56bdea12009-03-28 20:01:58 +00007529/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007530static int FAST_FUNC builtin_wait(char **argv)
Mike Frysinger56bdea12009-03-28 20:01:58 +00007531{
7532 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007533 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007534
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007535 if (*++argv == NULL) {
7536 /* Don't care about wait results */
7537 /* Note 1: must wait until there are no more children */
7538 /* Note 2: must be interruptible */
7539 /* Examples:
7540 * $ sleep 3 & sleep 6 & wait
7541 * [1] 30934 sleep 3
7542 * [2] 30935 sleep 6
7543 * [1] Done sleep 3
7544 * [2] Done sleep 6
7545 * $ sleep 3 & sleep 6 & wait
7546 * [1] 30936 sleep 3
7547 * [2] 30937 sleep 6
7548 * [1] Done sleep 3
7549 * ^C <-- after ~4 sec from keyboard
7550 * $
7551 */
7552 sigaddset(&G.blocked_set, SIGCHLD);
7553 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7554 while (1) {
7555 checkjobs(NULL);
7556 if (errno == ECHILD)
7557 break;
7558 /* Wait for SIGCHLD or any other signal of interest */
7559 /* sigtimedwait with infinite timeout: */
7560 sig = sigwaitinfo(&G.blocked_set, NULL);
7561 if (sig > 0) {
7562 sig = check_and_run_traps(sig);
7563 if (sig && sig != SIGCHLD) { /* see note 2 */
7564 ret = 128 + sig;
7565 break;
7566 }
7567 }
7568 }
7569 sigdelset(&G.blocked_set, SIGCHLD);
7570 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7571 return ret;
7572 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007573
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007574 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007575 while (*argv) {
7576 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007577 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007578 /* mimic bash message */
7579 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007580 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007581 }
7582 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007583 if (WIFSIGNALED(status))
7584 ret = 128 + WTERMSIG(status);
7585 else if (WIFEXITED(status))
7586 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007587 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007588 ret = EXIT_FAILURE;
7589 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007590 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007591 ret = 127;
7592 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007593 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007594 }
7595
7596 return ret;
7597}
7598
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007599#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7600static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7601{
7602 if (argv[1]) {
7603 def = bb_strtou(argv[1], NULL, 10);
7604 if (errno || def < def_min || argv[2]) {
7605 bb_error_msg("%s: bad arguments", argv[0]);
7606 def = UINT_MAX;
7607 }
7608 }
7609 return def;
7610}
7611#endif
7612
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007613#if ENABLE_HUSH_LOOPS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007614static int FAST_FUNC builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007615{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007616 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007617 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007618 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007619 return EXIT_SUCCESS; /* bash compat */
7620 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007621 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007622
7623 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7624 if (depth == UINT_MAX)
7625 G.flag_break_continue = BC_BREAK;
7626 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007627 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007628
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007629 return EXIT_SUCCESS;
7630}
7631
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007632static int FAST_FUNC builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007633{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007634 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7635 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007636}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007637#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007638
7639#if ENABLE_HUSH_FUNCTIONS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007640static int FAST_FUNC builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007641{
7642 int rc;
7643
7644 if (G.flag_return_in_progress != -1) {
7645 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7646 return EXIT_FAILURE; /* bash compat */
7647 }
7648
7649 G.flag_return_in_progress = 1;
7650
7651 /* bash:
7652 * out of range: wraps around at 256, does not error out
7653 * non-numeric param:
7654 * f() { false; return qwe; }; f; echo $?
7655 * bash: return: qwe: numeric argument required <== we do this
7656 * 255 <== we also do this
7657 */
7658 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7659 return rc;
7660}
7661#endif