blob: fd839d0612d18515389cc0275107b64901d7c354 [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 *
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000045 * Bash stuff (maybe optionally enable?):
Mike Frysinger25a6ca02009-03-28 13:59:26 +000046 * &> and >& redirection of stdout+stderr
47 * Brace expansion
48 * reserved words: [[ ]] function select
Mike Frysinger6379bb42009-03-28 18:55:03 +000049 * substrings ${var:1:5}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000050 *
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000051 * TODOs:
52 * grep for "TODO" and fix (some of them are easy)
Denis Vlasenkofa4ca782009-04-16 12:00:15 +000053 * $var refs in function do not pick up values set by "var=val func"
Denis Vlasenko6b9e0532009-04-18 01:23:21 +000054 * builtins: ulimit
Eric Andersen25f27032001-04-26 23:22:31 +000055 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000056 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000057 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000058 */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020059#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000060#include <glob.h>
61/* #include <dmalloc.h> */
62#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000063# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000064#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000065#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000066#include "match.h"
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000067#ifndef PIPE_BUF
Denys Vlasenkocb6ff252009-05-04 00:14:30 +020068# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000069#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000070
Denis Vlasenko1943aec2009-04-09 14:15:57 +000071
Denys Vlasenko8d7be232009-05-25 16:38:32 +020072/* Build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000073#define LEAK_HUNTING 0
74#define BUILD_AS_NOMMU 0
75/* Enable/disable sanity checks. Ok to enable in production,
76 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
77 * Keeping 1 for now even in released versions.
78 */
79#define HUSH_DEBUG 1
Denys Vlasenko8d7be232009-05-25 16:38:32 +020080/* Slightly bigger (+200 bytes), but faster hush.
81 * So far it only enables a trick with counting SIGCHLDs and forks,
82 * which allows us to do fewer waitpid's.
83 * (we can detect a case where neither forks were done nor SIGCHLDs happened
84 * and therefore waitpid will return the same result as last time)
85 */
86#define ENABLE_HUSH_FAST 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +000087
88
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000089#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +000090# undef BB_MMU
91# undef USE_FOR_NOMMU
92# undef USE_FOR_MMU
93# define BB_MMU 0
94# define USE_FOR_NOMMU(...) __VA_ARGS__
95# define USE_FOR_MMU(...)
96#endif
97
Denis Vlasenko61befda2008-11-25 01:36:03 +000098#if defined SINGLE_APPLET_MAIN
99/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000100# undef CONFIG_FEATURE_SH_STANDALONE
101# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000102# undef IF_FEATURE_SH_STANDALONE
103# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000104# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000105# define IF_FEATURE_SH_STANDALONE(...)
106# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000107#endif
108
Denis Vlasenko05743d72008-02-10 12:10:08 +0000109#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000110# undef ENABLE_FEATURE_EDITING
111# define ENABLE_FEATURE_EDITING 0
112# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
113# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000114#endif
115
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000116/* Do we support ANY keywords? */
117#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000118# define HAS_KEYWORDS 1
119# define IF_HAS_KEYWORDS(...) __VA_ARGS__
120# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000121#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000122# define HAS_KEYWORDS 0
123# define IF_HAS_KEYWORDS(...)
124# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000125#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000126
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000127/* If you comment out one of these below, it will be #defined later
128 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000129#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000130/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000131#define debug_printf_parse(...) do {} while (0)
132#define debug_print_tree(a, b) do {} while (0)
133#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000134#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000135#define debug_printf_jobs(...) do {} while (0)
136#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000137#define debug_printf_glob(...) do {} while (0)
138#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000139#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000140#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000141
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000142#define ERR_PTR ((void*)(long)1)
143
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000144#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000145
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000146#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000147
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200148struct variable;
149
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000150static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
151
152/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000153 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000154 */
155#if !BB_MMU
156typedef struct nommu_save_t {
157 char **new_env;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200158 struct variable *old_vars;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000159 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000160 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000161} nommu_save_t;
162#endif
163
Denis Vlasenko55789c62008-06-18 16:30:42 +0000164/* The descrip member of this structure is only used to make
165 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000166static const struct {
167 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000168 signed char default_fd;
169 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000170} redir_table[] = {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000171 { 0, 0, "??" },
Eric Andersen25f27032001-04-26 23:22:31 +0000172 { O_RDONLY, 0, "<" },
173 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
174 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000175 { O_RDONLY, 0, "<<" },
176 { O_CREAT|O_RDWR, 1, "<>" },
177/* Should not be needed. Bogus default_fd helps in debugging */
178/* { O_RDONLY, 77, "<<" }, */
Eric Andersen25f27032001-04-26 23:22:31 +0000179};
180
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000181typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000182 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000183#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000184 RES_IF ,
185 RES_THEN ,
186 RES_ELIF ,
187 RES_ELSE ,
188 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000189#endif
190#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000191 RES_FOR ,
192 RES_WHILE ,
193 RES_UNTIL ,
194 RES_DO ,
195 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000196#endif
197#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000198 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000199#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000200#if ENABLE_HUSH_CASE
201 RES_CASE ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +0200202 /* three pseudo-keywords support contrived "case" syntax: */
203 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
204 RES_MATCH , /* "word)" */
205 RES_CASE_BODY, /* "this command is inside CASE" */
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000206 RES_ESAC ,
207#endif
208 RES_XXXX ,
209 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000210} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000211
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000212typedef struct o_string {
213 char *data;
214 int length; /* position where data is appended */
215 int maxlen;
216 /* Protect newly added chars against globbing
217 * (by prepending \ to *, ?, [, \) */
218 smallint o_escape;
219 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000220 /* At least some part of the string was inside '' or "",
221 * possibly empty one: word"", wo''rd etc. */
222 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000223 smallint has_empty_slot;
224 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
225} o_string;
226enum {
227 MAYBE_ASSIGNMENT = 0,
228 DEFINITELY_ASSIGNMENT = 1,
229 NOT_ASSIGNMENT = 2,
230 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
231};
232/* Used for initialization: o_string foo = NULL_O_STRING; */
233#define NULL_O_STRING { NULL }
234
235/* I can almost use ordinary FILE*. Is open_memstream() universally
236 * available? Where is it documented? */
237typedef struct in_str {
238 const char *p;
239 /* eof_flag=1: last char in ->p is really an EOF */
240 char eof_flag; /* meaningless if ->p == NULL */
241 char peek_buf[2];
242#if ENABLE_HUSH_INTERACTIVE
243 smallint promptme;
244 smallint promptmode; /* 0: PS1, 1: PS2 */
245#endif
246 FILE *file;
247 int (*get) (struct in_str *);
248 int (*peek) (struct in_str *);
249} in_str;
250#define i_getch(input) ((input)->get(input))
251#define i_peek(input) ((input)->peek(input))
252
Eric Andersen25f27032001-04-26 23:22:31 +0000253struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000254 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000255 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000256 int rd_fd; /* fd to redirect */
257 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
258 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000259 smallint rd_type; /* (enum redir_type) */
260 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000261 * and subsequently heredoc itself; and rd_dup is a bitmask:
262 * 1: do we need to trim leading tabs?
Denis Vlasenkoed055212009-04-11 10:37:10 +0000263 * 2: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000264 */
Eric Andersen25f27032001-04-26 23:22:31 +0000265};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000266typedef enum redir_type {
267 REDIRECT_INVALID = 0,
268 REDIRECT_INPUT = 1,
269 REDIRECT_OVERWRITE = 2,
270 REDIRECT_APPEND = 3,
271 REDIRECT_HEREDOC = 4,
272 REDIRECT_IO = 5,
273 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000274
275 REDIRFD_CLOSE = -3,
276 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000277 REDIRFD_TO_FILE = -1,
278 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000279
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000280 HEREDOC_SKIPTABS = 1,
281 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000282} redir_type;
283
Eric Andersen25f27032001-04-26 23:22:31 +0000284
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000285struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000286 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000287 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000288 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000289 smallint grp_type; /* GRP_xxx */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000290#define GRP_NORMAL 0
291#define GRP_SUBSHELL 1
292#if ENABLE_HUSH_FUNCTIONS
293# define GRP_FUNCTION 2
294#endif
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200295 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
296 struct pipe *group;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000297#if !BB_MMU
298 char *group_as_string;
299#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000300#if ENABLE_HUSH_FUNCTIONS
301 struct function *child_func;
302/* This field is used to prevent a bug here:
303 * while...do f1() {a;}; f1; f1 {b;}; f1; done
304 * When we execute "f1() {a;}" cmd, we create new function and clear
305 * cmd->group, cmd->group_as_string, cmd->argv[0].
306 * when we execute "f1 {b;}", we notice that f1 exists,
307 * and that it's "parent cmd" struct is still "alive",
308 * we put those fields back into cmd->xxx
309 * (struct function has ->parent_cmd ptr to facilitate that).
310 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
311 * Without this trick, loop would execute a;b;b;b;...
312 * instead of correct sequence a;b;a;b;...
313 * When command is freed, it severs the link
314 * (sets ->child_func->parent_cmd to NULL).
315 */
316#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000317 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000318/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
319 * and on execution these are substituted with their values.
320 * Substitution can make _several_ words out of one argv[n]!
321 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000322 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000323 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000324 struct redir_struct *redirects; /* I/O redirections */
325};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000326/* Is there anything in this command at all? */
327#define IS_NULL_CMD(cmd) \
328 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
329
Eric Andersen25f27032001-04-26 23:22:31 +0000330
331struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000332 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000333 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000334 int alive_cmds; /* number of commands running (not exited) */
335 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000336#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000337 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000338 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000339 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000340#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000341 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000342 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000343 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
344 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000345};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000346typedef enum pipe_style {
347 PIPE_SEQ = 1,
348 PIPE_AND = 2,
349 PIPE_OR = 3,
350 PIPE_BG = 4,
351} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000352/* Is there anything in this pipe at all? */
353#define IS_NULL_PIPE(pi) \
354 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000355
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000356/* This holds pointers to the various results of parsing */
357struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000358 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000359 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000360 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000361 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000362 /* last command in pipe (being constructed right now) */
363 struct command *command;
364 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000365 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000366#if !BB_MMU
367 o_string as_string;
368#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000369#if HAS_KEYWORDS
370 smallint ctx_res_w;
371 smallint ctx_inverted; /* "! cmd | cmd" */
372#if ENABLE_HUSH_CASE
373 smallint ctx_dsemicolon; /* ";;" seen */
374#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000375 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
376 int old_flag;
377 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000378 * example: "if pipe1; pipe2; then pipe3; fi"
379 * when we see "if" or "then", we malloc and copy current context,
380 * and make ->stack point to it. then we parse pipeN.
381 * when closing "then" / fi" / whatever is found,
382 * we move list_head into ->stack->command->group,
383 * copy ->stack into current context, and delete ->stack.
384 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000385 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000386 struct parse_context *stack;
387#endif
388};
389
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000390/* On program start, environ points to initial environment.
391 * putenv adds new pointers into it, unsetenv removes them.
392 * Neither of these (de)allocates the strings.
393 * setenv allocates new strings in malloc space and does putenv,
394 * and thus setenv is unusable (leaky) for shell's purposes */
395#define setenv(...) setenv_is_leaky_dont_use()
396struct variable {
397 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000398 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000399 int max_len; /* if > 0, name is part of initial env; else name is malloced */
400 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000401 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000402};
403
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000404enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000405 BC_BREAK = 1,
406 BC_CONTINUE = 2,
407};
408
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000409#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000410struct function {
411 struct function *next;
412 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000413 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000414 struct pipe *body;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000415#if !BB_MMU
416 char *body_as_string;
417#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000418};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000419#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000420
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000421
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000422/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000423/* Sorted roughly by size (smaller offsets == smaller code) */
424struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000425 /* interactive_fd != 0 means we are an interactive shell.
426 * If we are, then saved_tty_pgrp can also be != 0, meaning
427 * that controlling tty is available. With saved_tty_pgrp == 0,
428 * job control still works, but terminal signals
429 * (^C, ^Z, ^Y, ^\) won't work at all, and background
430 * process groups can only be created with "cmd &".
431 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
432 * to give tty to the foreground process group,
433 * and will take it back when the group is stopped (^Z)
434 * or killed (^C).
435 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000436#if ENABLE_HUSH_INTERACTIVE
437 /* 'interactive_fd' is a fd# open to ctty, if we have one
438 * _AND_ if we decided to act interactively */
439 int interactive_fd;
440 const char *PS1;
441 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000442# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000443#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000444# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000445#endif
446#if ENABLE_FEATURE_EDITING
447 line_input_t *line_input_state;
448#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000449 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000450 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000451#if ENABLE_HUSH_JOB
452 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000453 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000454 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000455 struct pipe *job_list;
Mike Frysinger38478a62009-05-20 04:48:06 -0400456# define G_saved_tty_pgrp (G.saved_tty_pgrp)
457#else
458# define G_saved_tty_pgrp 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000459#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000460 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000461#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000462 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000463#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000464#if ENABLE_HUSH_FUNCTIONS
465 /* 0: outside of a function (or sourced file)
466 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000467 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000468 */
469 smallint flag_return_in_progress;
470#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000471 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000472 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000473 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000474 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000475 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000476 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000477 /* how many non-NULL argv's we have. NB: $# + 1 */
478 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000479 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000480#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000481 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000482#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000483#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000484 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000485 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000486#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000487 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000488 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000489 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000490 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000491#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000492 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000493#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000494 /* Signal and trap handling */
Denys Vlasenko8d7be232009-05-25 16:38:32 +0200495#if ENABLE_HUSH_FAST
496 unsigned count_SIGCHLD;
497 unsigned handled_SIGCHLD;
498 smallint last_waitpid_was_0;
499#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000500 /* which signals have non-DFL handler (even with no traps set)? */
501 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000502 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000503 sigset_t blocked_set;
504 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000505#if HUSH_DEBUG
506 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000507 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000508#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000509 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000510};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000511#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000512/* Not #defining name to G.name - this quickly gets unwieldy
513 * (too many defines). Also, I actually prefer to see when a variable
514 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000515#define INIT_G() do { \
516 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
517} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000518
519
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000520/* Function prototypes for builtins */
521static int builtin_cd(char **argv);
522static int builtin_echo(char **argv);
523static int builtin_eval(char **argv);
524static int builtin_exec(char **argv);
525static int builtin_exit(char **argv);
526static int builtin_export(char **argv);
527#if ENABLE_HUSH_JOB
528static int builtin_fg_bg(char **argv);
529static int builtin_jobs(char **argv);
530#endif
531#if ENABLE_HUSH_HELP
532static int builtin_help(char **argv);
533#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000534#if HUSH_DEBUG
535static int builtin_memleak(char **argv);
536#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000537static int builtin_pwd(char **argv);
538static int builtin_read(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000539static int builtin_set(char **argv);
540static int builtin_shift(char **argv);
541static int builtin_source(char **argv);
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000542static int builtin_test(char **argv);
543static int builtin_trap(char **argv);
544static int builtin_true(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000545static int builtin_umask(char **argv);
546static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000547static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000548#if ENABLE_HUSH_LOOPS
549static int builtin_break(char **argv);
550static int builtin_continue(char **argv);
551#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000552#if ENABLE_HUSH_FUNCTIONS
553static int builtin_return(char **argv);
554#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000555
556/* Table of built-in functions. They can be forked or not, depending on
557 * context: within pipes, they fork. As simple commands, they do not.
558 * When used in non-forking context, they can change global variables
559 * in the parent shell process. If forked, of course they cannot.
560 * For example, 'unset foo | whatever' will parse and run, but foo will
561 * still be set at the end. */
562struct built_in_command {
563 const char *cmd;
564 int (*function)(char **argv);
565#if ENABLE_HUSH_HELP
566 const char *descr;
567#define BLTIN(cmd, func, help) { cmd, func, help }
568#else
569#define BLTIN(cmd, func, help) { cmd, func }
570#endif
571};
572
573/* For now, echo and test are unconditionally enabled.
574 * Maybe make it configurable? */
575static const struct built_in_command bltins[] = {
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000576 BLTIN("." , builtin_source , "Run commands in a file"),
577 BLTIN(":" , builtin_true , "No-op"),
578 BLTIN("[" , builtin_test , "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000579#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000580 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000581#endif
582#if ENABLE_HUSH_LOOPS
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000583 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000584#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000585 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000586#if ENABLE_HUSH_LOOPS
587 BLTIN("continue", builtin_continue, "Start new loop iteration"),
588#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000589 BLTIN("echo" , builtin_echo , "Write to stdout"),
590 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
591 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
592 BLTIN("exit" , builtin_exit , "Exit"),
593 BLTIN("export" , builtin_export , "Set environment variable"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000594#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000595 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000596#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000597#if ENABLE_HUSH_HELP
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000598 BLTIN("help" , builtin_help , "List shell built-in commands"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000599#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000600#if ENABLE_HUSH_JOB
601 BLTIN("jobs" , builtin_jobs , "List active jobs"),
602#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000603#if HUSH_DEBUG
604 BLTIN("memleak" , builtin_memleak , "Debug tool"),
605#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000606 BLTIN("pwd" , builtin_pwd , "Print current directory"),
607 BLTIN("read" , builtin_read , "Input environment variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000608#if ENABLE_HUSH_FUNCTIONS
609 BLTIN("return" , builtin_return , "Return from a function"),
610#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000611 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
612 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
613 BLTIN("test" , builtin_test , "Test condition"),
614 BLTIN("trap" , builtin_trap , "Trap signals"),
615// BLTIN("ulimit" , builtin_return , "Control resource limits"),
616 BLTIN("umask" , builtin_umask , "Set file creation mask"),
617 BLTIN("unset" , builtin_unset , "Unset environment variable"),
618 BLTIN("wait" , builtin_wait , "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000619};
620
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000621
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000622/* Debug printouts.
623 */
624#if HUSH_DEBUG
625/* prevent disasters with G.debug_indent < 0 */
626# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
627# define debug_enter() (G.debug_indent++)
628# define debug_leave() (G.debug_indent--)
629#else
630# define indent() ((void)0)
631# define debug_enter() ((void)0)
632# define debug_leave() ((void)0)
633#endif
634
635#ifndef debug_printf
636# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
637#endif
638
639#ifndef debug_printf_parse
640# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
641#endif
642
643#ifndef debug_printf_exec
644#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
645#endif
646
647#ifndef debug_printf_env
648# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
649#endif
650
651#ifndef debug_printf_jobs
652# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
653# define DEBUG_JOBS 1
654#else
655# define DEBUG_JOBS 0
656#endif
657
658#ifndef debug_printf_expand
659# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
660# define DEBUG_EXPAND 1
661#else
662# define DEBUG_EXPAND 0
663#endif
664
665#ifndef debug_printf_glob
666# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
667# define DEBUG_GLOB 1
668#else
669# define DEBUG_GLOB 0
670#endif
671
672#ifndef debug_printf_list
673# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
674#endif
675
676#ifndef debug_printf_subst
677# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
678#endif
679
680#ifndef debug_printf_clean
681# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
682# define DEBUG_CLEAN 1
683#else
684# define DEBUG_CLEAN 0
685#endif
686
687#if DEBUG_EXPAND
688static void debug_print_strings(const char *prefix, char **vv)
689{
690 indent();
691 fprintf(stderr, "%s:\n", prefix);
692 while (*vv)
693 fprintf(stderr, " '%s'\n", *vv++);
694}
695#else
696#define debug_print_strings(prefix, vv) ((void)0)
697#endif
698
699
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000700/* Leak hunting. Use hush_leaktool.sh for post-processing.
701 */
702#if LEAK_HUNTING
703static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000704{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000705 void *ptr = xmalloc((size + 0xff) & ~0xff);
706 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
707 return ptr;
708}
709static void *xxrealloc(int lineno, void *ptr, size_t size)
710{
711 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
712 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
713 return ptr;
714}
715static char *xxstrdup(int lineno, const char *str)
716{
717 char *ptr = xstrdup(str);
718 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
719 return ptr;
720}
721static void xxfree(void *ptr)
722{
723 fdprintf(2, "free %p\n", ptr);
724 free(ptr);
725}
726#define xmalloc(s) xxmalloc(__LINE__, s)
727#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
728#define xstrdup(s) xxstrdup(__LINE__, s)
729#define free(p) xxfree(p)
730#endif
731
732
733/* Syntax and runtime errors. They always abort scripts.
734 * In interactive use they usually discard unparsed and/or unexecuted commands
735 * and return to the prompt.
736 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
737 */
738#if HUSH_DEBUG < 2
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000739# define die_if_script(lineno, fmt...) die_if_script(fmt)
740# define syntax_error(lineno, msg) syntax_error(msg)
741# define syntax_error_at(lineno, msg) syntax_error_at(msg)
742# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
743# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
744# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000745#endif
746
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000747static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000748{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000749 va_list p;
750
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000751#if HUSH_DEBUG >= 2
752 bb_error_msg("hush.c:%u", lineno);
753#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000754 va_start(p, fmt);
755 bb_verror_msg(fmt, p, NULL);
756 va_end(p);
757 if (!G_interactive_fd)
758 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000759}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000760
761static void syntax_error(unsigned lineno, const char *msg)
762{
763 if (msg)
764 die_if_script(lineno, "syntax error: %s", msg);
765 else
766 die_if_script(lineno, "syntax error", NULL);
767}
768
769static void syntax_error_at(unsigned lineno, const char *msg)
770{
771 die_if_script(lineno, "syntax error at '%s'", msg);
772}
773
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000774/* It so happens that all such cases are totally fatal
775 * even if shell is interactive: EOF while looking for closing
776 * delimiter. There is nowhere to read stuff from after that,
777 * it's EOF! The only choice is to terminate.
778 */
779static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000780static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000781{
782 char msg[2];
783 msg[0] = ch;
784 msg[1] = '\0';
785 die_if_script(lineno, "syntax error: unterminated %s", msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000786 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000787}
788
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000789static void syntax_error_unterm_str(unsigned lineno, const char *s)
790{
791 die_if_script(lineno, "syntax error: unterminated %s", s);
792}
793
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200794static void syntax_error_unexpected_ch(unsigned lineno, int ch)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000795{
796 char msg[2];
797 msg[0] = ch;
798 msg[1] = '\0';
Denys Vlasenkob1cfc452009-05-02 17:18:34 +0200799 die_if_script(lineno, "syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000800}
801
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000802#if HUSH_DEBUG < 2
803# undef die_if_script
804# undef syntax_error
805# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000806# undef syntax_error_unterm_ch
807# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000808# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000809#else
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000810# define die_if_script(fmt...) die_if_script(__LINE__, fmt)
811# define syntax_error(msg) syntax_error(__LINE__, msg)
812# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
813# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
814# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
815# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000816#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000817
Denis Vlasenko552433b2009-04-04 19:29:21 +0000818
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000819#if ENABLE_HUSH_INTERACTIVE
820static void cmdedit_update_prompt(void);
821#else
822# define cmdedit_update_prompt()
823#endif
824
825
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000826/* Utility functions
827 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000828static int glob_needed(const char *s)
829{
830 while (*s) {
831 if (*s == '\\')
832 s++;
833 if (*s == '*' || *s == '[' || *s == '?')
834 return 1;
835 s++;
836 }
837 return 0;
838}
839
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000840static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000841{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000842 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000843 return 0;
844 s++;
845 while (isalnum(*s) || *s == '_')
846 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000847 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000848}
849
Denis Vlasenko55789c62008-06-18 16:30:42 +0000850/* Replace each \x with x in place, return ptr past NUL. */
851static char *unbackslash(char *src)
852{
853 char *dst = src;
854 while (1) {
855 if (*src == '\\')
856 src++;
857 if ((*dst++ = *src++) == '\0')
858 break;
859 }
860 return dst;
861}
862
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000863static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000864{
865 int i;
866 unsigned count1;
867 unsigned count2;
868 char **v;
869
870 v = strings;
871 count1 = 0;
872 if (v) {
873 while (*v) {
874 count1++;
875 v++;
876 }
877 }
878 count2 = 0;
879 v = add;
880 while (*v) {
881 count2++;
882 v++;
883 }
884 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
885 v[count1 + count2] = NULL;
886 i = count2;
887 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000888 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000889 return v;
890}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000891#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000892static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
893{
894 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
895 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
896 return ptr;
897}
898#define add_strings_to_strings(strings, add, need_to_dup) \
899 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
900#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000901
Denys Vlasenkocb6ff252009-05-04 00:14:30 +0200902/* Note: takes ownership of "add" ptr (it is not strdup'ed) */
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000903static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000904{
905 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000906 v[0] = add;
907 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000908 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000909}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000910#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000911static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
912{
913 char **ptr = add_string_to_strings(strings, add);
914 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
915 return ptr;
916}
917#define add_string_to_strings(strings, add) \
918 xx_add_string_to_strings(__LINE__, strings, add)
919#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000920
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200921static void free_strings(char **strings)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000922{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000923 char **v;
924
925 if (!strings)
926 return;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000927 v = strings;
928 while (*v) {
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +0200929 free(*v);
930 v++;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000931 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000932 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000933}
934
Denis Vlasenko76d50412008-06-10 16:19:39 +0000935
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000936/* Helpers for setting new $n and restoring them back
937 */
938typedef struct save_arg_t {
939 char *sv_argv0;
940 char **sv_g_argv;
941 int sv_g_argc;
942 smallint sv_g_malloced;
943} save_arg_t;
944
945static void save_and_replace_G_args(save_arg_t *sv, char **argv)
946{
947 int n;
948
949 sv->sv_argv0 = argv[0];
950 sv->sv_g_argv = G.global_argv;
951 sv->sv_g_argc = G.global_argc;
952 sv->sv_g_malloced = G.global_args_malloced;
953
954 argv[0] = G.global_argv[0]; /* retain $0 */
955 G.global_argv = argv;
956 G.global_args_malloced = 0;
957
958 n = 1;
959 while (*++argv)
960 n++;
961 G.global_argc = n;
962}
963
964static void restore_G_args(save_arg_t *sv, char **argv)
965{
966 char **pp;
967
968 if (G.global_args_malloced) {
969 /* someone ran "set -- arg1 arg2 ...", undo */
970 pp = G.global_argv;
971 while (*++pp) /* note: does not free $0 */
972 free(*pp);
973 free(G.global_argv);
974 }
975 argv[0] = sv->sv_argv0;
976 G.global_argv = sv->sv_g_argv;
977 G.global_argc = sv->sv_g_argc;
978 G.global_args_malloced = sv->sv_g_malloced;
979}
980
981
Denis Vlasenkod5762932009-03-31 11:22:57 +0000982/* Basic theory of signal handling in shell
983 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000984 * This does not describe what hush does, rather, it is current understanding
985 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000986 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
987 *
988 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
989 * is finished or backgrounded. It is the same in interactive and
990 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000991 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000992 * ^C or ^Z from keyboard seem to execute "at once" because it usually
993 * backgrounds (i.e. stops) or kills all members of currently running
994 * pipe.
995 *
996 * Wait builtin in interruptible by signals for which user trap is set
997 * or by SIGINT in interactive shell.
998 *
999 * Trap handlers will execute even within trap handlers. (right?)
1000 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001001 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001002 *
1003 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001004 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001005 *
1006 * Commands run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001007 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001008 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001009 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
1010 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001011 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001012 * Siganls which differ from SIG_DFL action
1013 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001014 *
1015 * SIGQUIT: ignore
1016 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001017 * SIGHUP (interactive):
1018 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001019 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001020 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1021 * that all pipe members are stopped. Try this in bash:
1022 * while :; do :; done - ^Z does not background it
1023 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001024 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001025 * of the command line, show prompt. NB: ^C does not send SIGINT
1026 * to interactive shell while shell is waiting for a pipe,
1027 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001028 * Example 1: this waits 5 sec, but does not execute ls:
1029 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1030 * Example 2: this does not wait and does not execute ls:
1031 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1032 * Example 3: this does not wait 5 sec, but executes ls:
1033 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001034 *
1035 * (What happens to signals which are IGN on shell start?)
1036 * (What happens with signal mask on shell start?)
1037 *
1038 * Implementation in hush
1039 * ======================
1040 * We use in-kernel pending signal mask to determine which signals were sent.
1041 * We block all signals which we don't want to take action immediately,
1042 * i.e. we block all signals which need to have special handling as described
1043 * above, and all signals which have traps set.
1044 * After each pipe execution, we extract any pending signals via sigtimedwait()
1045 * and act on them.
1046 *
1047 * unsigned non_DFL_mask: a mask of such "special" signals
1048 * sigset_t blocked_set: current blocked signal set
1049 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001050 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001051 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001052 * "trap 'cmd' SIGxxx":
1053 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001054 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001055 * unblock signals with special interactive handling
1056 * (child shell is not interactive),
1057 * unset all traps (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001058 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001059 * POSIX says pending signal mask is cleared in child - no need to clear it.
1060 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001061 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001062 * Note: as a result, we do not use signal handlers much. The only uses
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001063 * are to count SIGCHLDs
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001064 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001065 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001066enum {
1067 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001068 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001069 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001070 | (1 << SIGHUP)
1071 ,
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001072 SPECIAL_JOB_SIGS = 0
Mike Frysinger38478a62009-05-20 04:48:06 -04001073#if ENABLE_HUSH_JOB
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001074 | (1 << SIGTTIN)
1075 | (1 << SIGTTOU)
1076 | (1 << SIGTSTP)
1077#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001078};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001079
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001080#if ENABLE_HUSH_FAST
1081static void SIGCHLD_handler(int sig UNUSED_PARAM)
1082{
1083 G.count_SIGCHLD++;
1084//bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1085}
1086#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001087
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001088#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001089
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001090/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1091#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001092/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001093#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1094
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001095/* Restores tty foreground process group, and exits.
1096 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001097 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001098 * or called directly with -EXITCODE.
1099 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001100static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001101static void sigexit(int sig)
1102{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001103 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001104 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001105
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001106 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001107 * tty pgrp then, only top-level shell process does that */
Mike Frysinger38478a62009-05-20 04:48:06 -04001108 if (G_saved_tty_pgrp && getpid() == G.root_pid)
1109 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001110
1111 /* Not a signal, just exit */
1112 if (sig <= 0)
1113 _exit(- sig);
1114
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001115 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001116}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001117#else
1118
1119#define disable_restore_tty_pgrp_on_exit() ((void)0)
1120#define enable_restore_tty_pgrp_on_exit() ((void)0)
1121
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001122#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001123
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001124/* Restores tty foreground process group, and exits. */
1125static void hush_exit(int exitcode) NORETURN;
1126static void hush_exit(int exitcode)
1127{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001128 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1129 /* Prevent recursion:
1130 * trap "echo Hi; exit" EXIT; exit
1131 */
1132 char *argv[] = { NULL, G.traps[0], NULL };
1133 G.traps[0] = NULL;
1134 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001135 builtin_eval(argv);
1136 free(argv[1]);
1137 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001138
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001139#if ENABLE_HUSH_JOB
1140 fflush(NULL); /* flush all streams */
1141 sigexit(- (exitcode & 0xff));
1142#else
1143 exit(exitcode);
1144#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001145}
1146
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001147static int check_and_run_traps(int sig)
1148{
1149 static const struct timespec zero_timespec = { 0, 0 };
1150 smalluint save_rcode;
1151 int last_sig = 0;
1152
1153 if (sig)
1154 goto jump_in;
1155 while (1) {
1156 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1157 if (sig <= 0)
1158 break;
1159 jump_in:
1160 last_sig = sig;
1161 if (G.traps && G.traps[sig]) {
1162 if (G.traps[sig][0]) {
1163 /* We have user-defined handler */
1164 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1165 save_rcode = G.last_exitcode;
1166 builtin_eval(argv);
1167 free(argv[1]);
1168 G.last_exitcode = save_rcode;
1169 } /* else: "" trap, ignoring signal */
1170 continue;
1171 }
1172 /* not a trap: special action */
1173 switch (sig) {
Denys Vlasenko8d7be232009-05-25 16:38:32 +02001174#if ENABLE_HUSH_FAST
1175 case SIGCHLD:
1176 G.count_SIGCHLD++;
1177//bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1178 break;
1179#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001180 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001181 /* Builtin was ^C'ed, make it look prettier: */
1182 bb_putchar('\n');
1183 G.flag_SIGINT = 1;
1184 break;
1185#if ENABLE_HUSH_JOB
1186 case SIGHUP: {
1187 struct pipe *job;
1188 /* bash is observed to signal whole process groups,
1189 * not individual processes */
1190 for (job = G.job_list; job; job = job->next) {
1191 if (job->pgrp <= 0)
1192 continue;
1193 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1194 if (kill(- job->pgrp, SIGHUP) == 0)
1195 kill(- job->pgrp, SIGCONT);
1196 }
1197 sigexit(SIGHUP);
1198 }
1199#endif
1200 default: /* ignored: */
1201 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1202 break;
1203 }
1204 }
1205 return last_sig;
1206}
1207
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001208
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001209static const char *set_cwd(void)
1210{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001211 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1212 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001213 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001214 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001215 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1216 if (!G.cwd)
1217 G.cwd = bb_msg_unknown;
1218 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001219}
1220
Denis Vlasenko83506862007-11-23 13:11:42 +00001221
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001222/*
1223 * Shell and environment variable support
1224 */
1225static struct variable **get_ptr_to_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001226{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001227 struct variable **pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001228 struct variable *cur;
1229 int len;
1230
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001231 len = strlen(name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001232 pp = &G.top_var;
1233 while ((cur = *pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001234 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001235 return pp;
1236 pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001237 }
1238 return NULL;
1239}
1240
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001241static struct variable *get_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001242{
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001243 struct variable **pp = get_ptr_to_local_var(name);
1244 if (pp)
1245 return *pp;
1246 return NULL;
1247}
1248
1249static const char *get_local_var_value(const char *name)
1250{
1251 struct variable **pp = get_ptr_to_local_var(name);
1252 if (pp)
1253 return strchr((*pp)->varstr, '=') + 1;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001254 return NULL;
1255}
1256
1257/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001258 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001259 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001260 * 0: do not change export flag
1261 * (if creating new variable, flag will be 0)
1262 * 1: set export flag and putenv the variable
1263 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001264 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001265 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001266#if BB_MMU
1267#define set_local_var(str, flg_export, flg_read_only) \
1268 set_local_var(str, flg_export)
1269#endif
1270static int set_local_var(char *str, int flg_export, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001271{
1272 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001273 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001274 int name_len;
1275
Denis Vlasenko950bd722009-04-21 11:23:56 +00001276 eq_sign = strchr(str, '=');
1277 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001278 free(str);
1279 return -1;
1280 }
1281
Denis Vlasenko950bd722009-04-21 11:23:56 +00001282 name_len = eq_sign - str + 1; /* including '=' */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001283 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1284 while (1) {
1285 if (strncmp(cur->varstr, str, name_len) != 0) {
1286 if (!cur->next) {
1287 /* Bail out. Note that now cur points
1288 * to last var in linked list */
1289 break;
1290 }
1291 cur = cur->next;
1292 continue;
1293 }
1294 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001295 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001296#if !BB_MMU
1297 if (!flg_read_only)
1298#endif
1299 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001300 free(str);
1301 return -1;
1302 }
Denis Vlasenko950bd722009-04-21 11:23:56 +00001303 if (flg_export == -1) {
1304 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1305 *eq_sign = '\0';
1306 unsetenv(str);
1307 *eq_sign = '=';
1308 }
1309 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001310 free_and_exp:
1311 free(str);
1312 goto exp;
1313 }
1314 if (cur->max_len >= strlen(str)) {
1315 /* This one is from startup env, reuse space */
1316 strcpy(cur->varstr, str);
1317 goto free_and_exp;
1318 }
1319 /* max_len == 0 signifies "malloced" var, which we can
1320 * (and has to) free */
1321 if (!cur->max_len)
1322 free(cur->varstr);
1323 cur->max_len = 0;
1324 goto set_str_and_exp;
1325 }
1326
1327 /* Not found - create next variable struct */
1328 cur->next = xzalloc(sizeof(*cur));
1329 cur = cur->next;
1330
1331 set_str_and_exp:
1332 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001333#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001334 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001335#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001336 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001337 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001338 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001339 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1340 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001341 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001342 if (flg_export == -1) {
1343 cur->flg_export = 0;
1344 /* unsetenv was already done */
1345 } else {
1346 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1347 return putenv(cur->varstr);
1348 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001349 }
1350 return 0;
1351}
1352
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001353static int unset_local_var_len(const char *name, int name_len)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001354{
1355 struct variable *cur;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001356 struct variable **var_pp;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001357
1358 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001359 return EXIT_SUCCESS;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001360 var_pp = &G.top_var;
1361 while ((cur = *var_pp) != NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001362 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1363 if (cur->flg_read_only) {
1364 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001365 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001366 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001367 *var_pp = cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001368 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1369 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001370 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1371 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001372 if (!cur->max_len)
1373 free(cur->varstr);
1374 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001375 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001376 }
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001377 var_pp = &cur->next;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001378 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001379 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001380}
1381
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001382static int unset_local_var(const char *name)
1383{
1384 return unset_local_var_len(name, strlen(name));
1385}
1386
1387static void unset_vars(char **strings)
1388{
1389 char **v;
1390
1391 if (!strings)
1392 return;
1393 v = strings;
1394 while (*v) {
1395 const char *eq = strchrnul(*v, '=');
1396 unset_local_var_len(*v, (int)(eq - *v));
1397 v++;
1398 }
1399 free(strings);
1400}
1401
Mike Frysinger98c52642009-04-02 10:02:37 +00001402#if ENABLE_SH_MATH_SUPPORT
1403#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1404#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1405static char *endofname(const char *name)
1406{
1407 char *p;
1408
1409 p = (char *) name;
1410 if (!is_name(*p))
1411 return p;
1412 while (*++p) {
1413 if (!is_in_name(*p))
1414 break;
1415 }
1416 return p;
1417}
1418
1419static void arith_set_local_var(const char *name, const char *val, int flags)
1420{
1421 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001422 char *var = xasprintf("%s=%s", name, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001423 set_local_var(var, flags, 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001424}
1425#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001426
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001427
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001428/*
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001429 * Helpers for "var1=val1 var2=val2 cmd" feature
1430 */
1431static void add_vars(struct variable *var)
1432{
1433 struct variable *next;
1434
1435 while (var) {
1436 next = var->next;
1437 var->next = G.top_var;
1438 G.top_var = var;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001439 if (var->flg_export) {
1440 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001441 putenv(var->varstr);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001442 } else {
1443 debug_printf_env("%s: restoring local '%s'\n", __func__, var->varstr);
1444 }
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001445 var = next;
1446 }
1447}
1448
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001449static struct variable *set_vars_and_save_old(char **strings)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001450{
1451 char **s;
1452 struct variable *old = NULL;
1453
1454 if (!strings)
1455 return old;
1456 s = strings;
1457 while (*s) {
1458 struct variable *var_p;
1459 struct variable **var_pp;
1460 char *eq;
1461
1462 eq = strchr(*s, '=');
1463 if (eq) {
1464 *eq = '\0';
1465 var_pp = get_ptr_to_local_var(*s);
1466 *eq = '=';
1467 if (var_pp) {
1468 /* Remove variable from global linked list */
1469 var_p = *var_pp;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02001470 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02001471 *var_pp = var_p->next;
1472 /* Add it to returned list */
1473 var_p->next = old;
1474 old = var_p;
1475 }
1476 set_local_var(*s, 1, 0);
1477 }
1478 s++;
1479 }
1480 return old;
1481}
1482
1483
1484/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001485 * in_str support
1486 */
1487static int static_get(struct in_str *i)
1488{
1489 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001490 if (ch != '\0')
1491 return ch;
1492 i->p--;
1493 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001494}
1495
1496static int static_peek(struct in_str *i)
1497{
1498 return *i->p;
1499}
1500
1501#if ENABLE_HUSH_INTERACTIVE
1502
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001503static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001504{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001505 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001506 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001507 if (G.PS1 == NULL)
1508 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001509 G.PS2 = get_local_var_value("PS2");
Denys Vlasenko690ad242009-04-30 21:24:24 +02001510 } else {
Mike Frysingerec2c6552009-03-28 12:24:44 +00001511 G.PS1 = NULL;
Denys Vlasenko690ad242009-04-30 21:24:24 +02001512 }
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001513 if (G.PS2 == NULL)
1514 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001515}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001516
1517static const char* setup_prompt_string(int promptmode)
1518{
1519 const char *prompt_str;
1520 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001521 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1522 /* Set up the prompt */
1523 if (promptmode == 0) { /* PS1 */
1524 free((char*)G.PS1);
1525 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1526 prompt_str = G.PS1;
1527 } else
1528 prompt_str = G.PS2;
1529 } else
1530 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001531 debug_printf("result '%s'\n", prompt_str);
1532 return prompt_str;
1533}
1534
1535static void get_user_input(struct in_str *i)
1536{
1537 int r;
1538 const char *prompt_str;
1539
1540 prompt_str = setup_prompt_string(i->promptmode);
1541#if ENABLE_FEATURE_EDITING
1542 /* Enable command line editing only while a command line
1543 * is actually being read */
1544 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001545 G.flag_SIGINT = 0;
1546 /* buglet: SIGINT will not make new prompt to appear _at once_,
1547 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001548 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001549 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001550 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001551 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001552 i->eof_flag = (r < 0);
1553 if (i->eof_flag) { /* EOF/error detected */
1554 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1555 G.user_input_buf[1] = '\0';
1556 }
1557#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001558 do {
1559 G.flag_SIGINT = 0;
1560 fputs(prompt_str, stdout);
1561 fflush(stdout);
1562 G.user_input_buf[0] = r = fgetc(i->file);
1563 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001564//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001565 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001566 i->eof_flag = (r == EOF);
1567#endif
1568 i->p = G.user_input_buf;
1569}
1570
1571#endif /* INTERACTIVE */
1572
1573/* This is the magic location that prints prompts
1574 * and gets data back from the user */
1575static int file_get(struct in_str *i)
1576{
1577 int ch;
1578
1579 /* If there is data waiting, eat it up */
1580 if (i->p && *i->p) {
1581#if ENABLE_HUSH_INTERACTIVE
1582 take_cached:
1583#endif
1584 ch = *i->p++;
1585 if (i->eof_flag && !*i->p)
1586 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001587 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001588 } else {
1589 /* need to double check i->file because we might be doing something
1590 * more complicated by now, like sourcing or substituting. */
1591#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001592 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001593 do {
1594 get_user_input(i);
1595 } while (!*i->p); /* need non-empty line */
1596 i->promptmode = 1; /* PS2 */
1597 i->promptme = 0;
1598 goto take_cached;
1599 }
1600#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001601 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001602 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001603 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001604#if ENABLE_HUSH_INTERACTIVE
1605 if (ch == '\n')
1606 i->promptme = 1;
1607#endif
1608 return ch;
1609}
1610
Denis Vlasenko913a2012009-04-05 22:17:04 +00001611/* All callers guarantee this routine will never
1612 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001613 */
1614static int file_peek(struct in_str *i)
1615{
1616 int ch;
1617 if (i->p && *i->p) {
1618 if (i->eof_flag && !i->p[1])
1619 return EOF;
1620 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001621 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001622 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001623 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001624 i->eof_flag = (ch == EOF);
1625 i->peek_buf[0] = ch;
1626 i->peek_buf[1] = '\0';
1627 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001628 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001629 return ch;
1630}
1631
1632static void setup_file_in_str(struct in_str *i, FILE *f)
1633{
1634 i->peek = file_peek;
1635 i->get = file_get;
1636#if ENABLE_HUSH_INTERACTIVE
1637 i->promptme = 1;
1638 i->promptmode = 0; /* PS1 */
1639#endif
1640 i->file = f;
1641 i->p = NULL;
1642}
1643
1644static void setup_string_in_str(struct in_str *i, const char *s)
1645{
1646 i->peek = static_peek;
1647 i->get = static_get;
1648#if ENABLE_HUSH_INTERACTIVE
1649 i->promptme = 1;
1650 i->promptmode = 0; /* PS1 */
1651#endif
1652 i->p = s;
1653 i->eof_flag = 0;
1654}
1655
1656
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001657/*
1658 * o_string support
1659 */
1660#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001661
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001662static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001663{
1664 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001665 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001666 if (o->data)
1667 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001668}
1669
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001670static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001671{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001672 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001673 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001674}
1675
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001676static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1677{
1678 free(o->data);
1679}
1680
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001681static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001682{
1683 if (o->length + len > o->maxlen) {
1684 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1685 o->data = xrealloc(o->data, 1 + o->maxlen);
1686 }
1687}
1688
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001689static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001690{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001691 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1692 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001693 o->data[o->length] = ch;
1694 o->length++;
1695 o->data[o->length] = '\0';
1696}
1697
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001698static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001699{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001700 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001701 memcpy(&o->data[o->length], str, len);
1702 o->length += len;
1703 o->data[o->length] = '\0';
1704}
1705
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001706#if !BB_MMU
1707static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001708{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001709 o_addblock(o, str, strlen(str));
1710}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001711static void nommu_addchr(o_string *o, int ch)
1712{
1713 if (o)
1714 o_addchr(o, ch);
1715}
1716#else
1717#define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001718#endif
1719
1720static void o_addstr_with_NUL(o_string *o, const char *str)
1721{
1722 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001723}
1724
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001725static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001726{
1727 while (len) {
1728 o_addchr(o, *str);
1729 if (*str++ == '\\'
1730 && (*str != '*' && *str != '?' && *str != '[')
1731 ) {
1732 o_addchr(o, '\\');
1733 }
1734 len--;
1735 }
1736}
1737
Eric Andersen25f27032001-04-26 23:22:31 +00001738/* My analysis of quoting semantics tells me that state information
1739 * is associated with a destination, not a source.
1740 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001741static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001742{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001743 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001744 char *found = strchr("*?[\\", ch);
1745 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001746 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001747 o_grow_by(o, sz);
1748 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001749 o->data[o->length] = '\\';
1750 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001751 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001752 o->data[o->length] = ch;
1753 o->length++;
1754 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001755}
1756
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001757static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001758{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001759 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001760 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001761 sz++;
1762 o->data[o->length] = '\\';
1763 o->length++;
1764 }
1765 o_grow_by(o, sz);
1766 o->data[o->length] = ch;
1767 o->length++;
1768 o->data[o->length] = '\0';
1769}
1770
1771static void o_addQstr(o_string *o, const char *str, int len)
1772{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001773 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001774 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001775 return;
1776 }
1777 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001778 char ch;
1779 int sz;
1780 int ordinary_cnt = strcspn(str, "*?[\\");
1781 if (ordinary_cnt > len) /* paranoia */
1782 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001783 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001784 if (ordinary_cnt == len)
1785 return;
1786 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001787 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001788
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001789 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001790 sz = 1;
1791 if (ch) { /* it is necessarily one of "*?[\\" */
1792 sz++;
1793 o->data[o->length] = '\\';
1794 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001795 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001796 o_grow_by(o, sz);
1797 o->data[o->length] = ch;
1798 o->length++;
1799 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001800 }
1801}
1802
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001803/* A special kind of o_string for $VAR and `cmd` expansion.
1804 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001805 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001806 * list[i] contains an INDEX (int!) into this string data.
1807 * It means that if list[] needs to grow, data needs to be moved higher up
1808 * but list[i]'s need not be modified.
1809 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001810 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001811 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1812 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001813#if DEBUG_EXPAND || DEBUG_GLOB
1814static void debug_print_list(const char *prefix, o_string *o, int n)
1815{
1816 char **list = (char**)o->data;
1817 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1818 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001819
1820 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001821 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1822 prefix, list, n, string_start, o->length, o->maxlen);
1823 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001824 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001825 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1826 o->data + (int)list[i] + string_start,
1827 o->data + (int)list[i] + string_start);
1828 i++;
1829 }
1830 if (n) {
1831 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001832 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001833 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001834 }
1835}
1836#else
1837#define debug_print_list(prefix, o, n) ((void)0)
1838#endif
1839
1840/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1841 * in list[n] so that it points past last stored byte so far.
1842 * It returns n+1. */
1843static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001844{
1845 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001846 int string_start;
1847 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001848
1849 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001850 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1851 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001852 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001853 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001854 /* list[n] points to string_start, make space for 16 more pointers */
1855 o->maxlen += 0x10 * sizeof(list[0]);
1856 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001857 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001858 memmove(list + n + 0x10, list + n, string_len);
1859 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001860 } else {
1861 debug_printf_list("list[%d]=%d string_start=%d\n",
1862 n, string_len, string_start);
1863 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001864 } else {
1865 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001866 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1867 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001868 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1869 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001870 o->has_empty_slot = 0;
1871 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001872 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001873 return n + 1;
1874}
1875
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001876/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001877static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001878{
1879 char **list = (char**)o->data;
1880 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1881
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001882 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001883}
1884
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001885/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001886 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001887static int o_glob(o_string *o, int n)
1888{
1889 glob_t globdata;
1890 int gr;
1891 char *pattern;
1892
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001893 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001894 if (!o->data)
1895 return o_save_ptr_helper(o, n);
1896 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001897 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001898 if (!glob_needed(pattern)) {
1899 literal:
1900 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001901 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001902 return o_save_ptr_helper(o, n);
1903 }
1904
1905 memset(&globdata, 0, sizeof(globdata));
1906 gr = glob(pattern, 0, NULL, &globdata);
1907 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1908 if (gr == GLOB_NOSPACE)
1909 bb_error_msg_and_die("out of memory during glob");
1910 if (gr == GLOB_NOMATCH) {
1911 globfree(&globdata);
1912 goto literal;
1913 }
1914 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00001915 /* TODO: testcase for bad glob pattern behavior */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001916 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1917 }
1918 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1919 char **argv = globdata.gl_pathv;
1920 o->length = pattern - o->data; /* "forget" pattern */
1921 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001922 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001923 n = o_save_ptr_helper(o, n);
1924 argv++;
1925 if (!*argv)
1926 break;
1927 }
1928 }
1929 globfree(&globdata);
1930 if (DEBUG_GLOB)
1931 debug_print_list("o_glob returning", o, n);
1932 return n;
1933}
1934
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001935/* If o->o_glob == 1, glob the string so far remembered.
1936 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001937static int o_save_ptr(o_string *o, int n)
1938{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001939 if (o->o_glob) { /* if globbing is requested */
1940 /* If o->has_empty_slot, list[n] was already globbed
1941 * (if it was requested back then when it was filled)
1942 * so don't do that again! */
1943 if (!o->has_empty_slot)
1944 return o_glob(o, n); /* o_save_ptr_helper is inside */
1945 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001946 return o_save_ptr_helper(o, n);
1947}
1948
1949/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001950static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001951{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001952 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001953 int string_start;
1954
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001955 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1956 if (DEBUG_EXPAND)
1957 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001958 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001959 list = (char**)o->data;
1960 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1961 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001962 while (n) {
1963 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001964 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001965 }
1966 return list;
1967}
1968
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001969
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001970/* Expansion can recurse */
1971#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001972static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001973#endif
1974static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001975#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001976#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001977 parse_stream_dquoted(dest, input, dquote_end)
1978#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001979static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001980 o_string *dest,
1981 struct in_str *input,
1982 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001983
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001984/* expand_strvec_to_strvec() takes a list of strings, expands
1985 * all variable references within and returns a pointer to
1986 * a list of expanded strings, possibly with larger number
1987 * of strings. (Think VAR="a b"; echo $VAR).
1988 * This new list is allocated as a single malloc block.
1989 * NULL-terminated list of char* pointers is at the beginning of it,
1990 * followed by strings themself.
1991 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001992
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001993/* Store given string, finalizing the word and starting new one whenever
1994 * we encounter IFS char(s). This is used for expanding variable values.
1995 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1996static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001997{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001998 while (1) {
1999 int word_len = strcspn(str, G.ifs);
2000 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002001 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002002 o_addQstr(output, str, word_len);
2003 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002004 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002005 str += word_len;
2006 }
2007 if (!*str) /* EOL - do not finalize word */
2008 break;
2009 o_addchr(output, '\0');
2010 debug_print_list("expand_on_ifs", output, n);
2011 n = o_save_ptr(output, n);
2012 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00002013 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002014 debug_print_list("expand_on_ifs[1]", output, n);
2015 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002016}
2017
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002018/* Helper to expand $((...)) and heredoc body. These act as if
2019 * they are in double quotes, with the exception that they are not :).
2020 * Just the rules are similar: "expand only $var and `cmd`"
2021 *
2022 * Returns malloced string.
2023 * As an optimization, we return NULL if expansion is not needed.
2024 */
2025static char *expand_pseudo_dquoted(const char *str)
2026{
2027 char *exp_str;
2028 struct in_str input;
2029 o_string dest = NULL_O_STRING;
2030
2031 if (strchr(str, '$') == NULL
2032#if ENABLE_HUSH_TICK
2033 && strchr(str, '`') == NULL
2034#endif
2035 ) {
2036 return NULL;
2037 }
2038
2039 /* We need to expand. Example:
2040 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
2041 */
2042 setup_string_in_str(&input, str);
2043 parse_stream_dquoted(NULL, &dest, &input, EOF);
2044 //bb_error_msg("'%s' -> '%s'", str, dest.data);
2045 exp_str = expand_string_to_string(dest.data);
2046 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
2047 o_free_unsafe(&dest);
2048 return exp_str;
2049}
2050
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002051/* Expand all variable references in given string, adding words to list[]
2052 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2053 * to be filled). This routine is extremely tricky: has to deal with
2054 * variables/parameters with whitespace, $* and $@, and constructs like
2055 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2056static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002057{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002058 /* or_mask is either 0 (normal case) or 0x80
2059 * (expansion of right-hand side of assignment == 1-element expand.
2060 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00002061
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002062 char ored_ch;
2063 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002064
2065 ored_ch = 0;
2066
2067 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2068 debug_print_list("expand_vars_to_list", output, n);
2069 n = o_save_ptr(output, n);
2070 debug_print_list("expand_vars_to_list[0]", output, n);
2071
2072 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002073 char first_ch;
2074 int i;
2075 char *dyn_val = NULL;
2076 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002077#if ENABLE_HUSH_TICK
2078 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002079#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002080#if ENABLE_SH_MATH_SUPPORT
2081 char arith_buf[sizeof(arith_t)*3 + 2];
2082#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002083 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002084 debug_print_list("expand_vars_to_list[1]", output, n);
2085 arg = ++p;
2086 p = strchr(p, SPECIAL_VAR_SYMBOL);
2087
2088 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2089 /* "$@" is special. Even if quoted, it can still
2090 * expand to nothing (not even an empty string) */
2091 if ((first_ch & 0x7f) != '@')
2092 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002093
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002094 switch (first_ch & 0x7f) {
2095 /* Highest bit in first_ch indicates that var is double-quoted */
2096 case '$': /* pid */
2097 val = utoa(G.root_pid);
2098 break;
2099 case '!': /* bg pid */
2100 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2101 break;
2102 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002103 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104 break;
2105 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002106 if (arg[1] != SPECIAL_VAR_SYMBOL)
2107 /* actually, it's a ${#var} */
2108 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002109 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2110 break;
2111 case '*':
2112 case '@':
2113 i = 1;
2114 if (!G.global_argv[i])
2115 break;
2116 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2117 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002118 smallint sv = output->o_escape;
2119 /* unquoted var's contents should be globbed, so don't escape */
2120 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002121 while (G.global_argv[i]) {
2122 n = expand_on_ifs(output, n, G.global_argv[i]);
2123 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2124 if (G.global_argv[i++][0] && G.global_argv[i]) {
2125 /* this argv[] is not empty and not last:
2126 * put terminating NUL, start new word */
2127 o_addchr(output, '\0');
2128 debug_print_list("expand_vars_to_list[2]", output, n);
2129 n = o_save_ptr(output, n);
2130 debug_print_list("expand_vars_to_list[3]", output, n);
2131 }
2132 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002133 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002134 } else
2135 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2136 * and in this case should treat it like '$*' - see 'else...' below */
2137 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2138 while (1) {
2139 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2140 if (++i >= G.global_argc)
2141 break;
2142 o_addchr(output, '\0');
2143 debug_print_list("expand_vars_to_list[4]", output, n);
2144 n = o_save_ptr(output, n);
2145 }
2146 } else { /* quoted $*: add as one word */
2147 while (1) {
2148 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2149 if (!G.global_argv[++i])
2150 break;
2151 if (G.ifs[0])
2152 o_addchr(output, G.ifs[0]);
2153 }
2154 }
2155 break;
2156 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2157 /* "Empty variable", used to make "" etc to not disappear */
2158 arg++;
2159 ored_ch = 0x80;
2160 break;
2161#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002162 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002163 *p = '\0';
2164 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002165 /* Can't just stuff it into output o_string,
2166 * expanded result may need to be globbed
2167 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002169 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002170 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2171 val = subst_result.data;
2172 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002173#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002174#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002175 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002176 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002177 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002178 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002179 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002180
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002181 arg++; /* skip '+' */
2182 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002183 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002184
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002185 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002186 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002187 hooks.setvar = arith_set_local_var;
2188 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002189 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2190 free(exp_str);
2191
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002192 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002193 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002194 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002195 case -3:
2196 msg = "exponent less than 0";
2197 break;
2198 case -2:
2199 msg = "divide by 0";
2200 break;
2201 case -5:
2202 msg = "expression recursion loop detected";
2203 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002204 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002205 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002206 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002207 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002208 sprintf(arith_buf, arith_t_fmt, res);
2209 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002210 break;
2211 }
2212#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002213 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002214 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002215 bool exp_len = false;
2216 bool exp_null = false;
2217 char *var = arg;
2218 char exp_save = exp_save; /* for compiler */
2219 char exp_op = exp_op; /* for compiler */
2220 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002221 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002222
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002223 *p = '\0';
2224 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002225
2226 /* prepare for expansions */
2227 if (var[0] == '#') {
2228 /* handle length expansion ${#var} */
2229 exp_len = true;
2230 ++var;
2231 } else {
2232 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002233 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002234 if (!var[exp_off])
2235 exp_off = 0;
2236 if (exp_off) {
2237 exp_save = var[exp_off];
2238 exp_null = exp_save == ':';
2239 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002240 if (exp_null)
2241 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002242 exp_op = *exp_word++;
2243 var[exp_off] = '\0';
2244 }
2245 }
2246
2247 /* lookup the variable in question */
2248 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002249 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002250 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002251 if (i < G.global_argc)
2252 val = G.global_argv[i];
2253 /* else val remains NULL: $N with too big N */
2254 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002255 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002256
2257 /* handle any expansions */
2258 if (exp_len) {
2259 debug_printf_expand("expand: length of '%s' = ", val);
2260 val = utoa(val ? strlen(val) : 0);
2261 debug_printf_expand("%s\n", val);
2262 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002263 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002264 if (val) {
2265 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002266 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002267 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002268 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002269 if (exp_op == *exp_word) /* ## or %% */
2270 ++exp_word;
2271 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002272 loc = scan(dyn_val, exp_word, match_at_left);
2273 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002274 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002275 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002276 *loc = '\0';
2277 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002278 } else {
2279 /* we need to do an expansion */
2280 int exp_test = (!val || (exp_null && !val[0]));
2281 if (exp_op == '+')
2282 exp_test = !exp_test;
2283 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2284 exp_null ? "true" : "false", exp_test);
2285 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002286 if (exp_op == '?') {
2287//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002288 /* ${var?[error_msg_if_unset]} */
2289 /* ${var:?[error_msg_if_unset_or_null]} */
2290 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002291 die_if_script("%s: %s",
2292 var,
2293 exp_word[0] ? exp_word : "parameter null or not set"
2294 );
2295 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002296 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002297 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002298
Mike Frysingera4f331d2009-04-07 06:03:22 +00002299 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002300 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002301 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002302 /* mimic bash message */
2303 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002304 val = NULL;
2305 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002306 char *new_var = xasprintf("%s=%s", var, val);
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002307 set_local_var(new_var, 0, 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002308 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002309 }
2310 }
2311 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002312
Mike Frysinger6379bb42009-03-28 18:55:03 +00002313 var[exp_off] = exp_save;
2314 }
2315
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002316 arg[0] = first_ch;
2317#if ENABLE_HUSH_TICK
2318 store_val:
2319#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002320 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002321 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002323 /* unquoted var's contents should be globbed, so don't escape */
2324 smallint sv = output->o_escape;
2325 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002326 n = expand_on_ifs(output, n, val);
2327 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002328 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002329 }
2330 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002331 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002332 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002333 } /* default: */
2334 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002335
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002336 if (val) {
2337 o_addQstr(output, val, strlen(val));
2338 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002339 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002340 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002341 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002342 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002343
2344#if ENABLE_HUSH_TICK
2345 o_free(&subst_result);
2346#endif
2347 arg = ++p;
2348 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2349
2350 if (arg[0]) {
2351 debug_print_list("expand_vars_to_list[a]", output, n);
2352 /* this part is literal, and it was already pre-quoted
2353 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002354 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002355 debug_print_list("expand_vars_to_list[b]", output, n);
2356 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2357 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2358 ) {
2359 n--;
2360 /* allow to reuse list[n] later without re-growth */
2361 output->has_empty_slot = 1;
2362 } else {
2363 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002364 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002365 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002366}
2367
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002368static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002369{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002370 int n;
2371 char **list;
2372 char **v;
2373 o_string output = NULL_O_STRING;
2374
2375 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002376 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002377 /* (unquoted $var will temporarily switch it off) */
2378 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002379 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002380
2381 n = 0;
2382 v = argv;
2383 while (*v) {
2384 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2385 v++;
2386 }
2387 debug_print_list("expand_variables", &output, n);
2388
2389 /* output.data (malloced in one block) gets returned in "list" */
2390 list = o_finalize_list(&output, n);
2391 debug_print_strings("expand_variables[1]", list);
2392 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002393}
2394
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002395static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002396{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002397 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002398}
2399
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002400/* Used for expansion of right hand of assignments */
2401/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2402 * "v=/bin/c*" */
2403static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002404{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002405 char *argv[2], **list;
2406
2407 argv[0] = (char*)str;
2408 argv[1] = NULL;
2409 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2410 if (HUSH_DEBUG)
2411 if (!list[0] || list[1])
2412 bb_error_msg_and_die("BUG in varexp2");
2413 /* actually, just move string 2*sizeof(char*) bytes back */
2414 overlapping_strcpy((char*)list, list[0]);
2415 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2416 return (char*)list;
2417}
2418
2419/* Used for "eval" builtin */
2420static char* expand_strvec_to_string(char **argv)
2421{
2422 char **list;
2423
2424 list = expand_variables(argv, 0x80);
2425 /* Convert all NULs to spaces */
2426 if (list[0]) {
2427 int n = 1;
2428 while (list[n]) {
2429 if (HUSH_DEBUG)
2430 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2431 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002432 /* bash uses ' ' regardless of $IFS contents */
2433 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002434 n++;
2435 }
2436 }
2437 overlapping_strcpy((char*)list, list[0]);
2438 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2439 return (char*)list;
2440}
2441
2442static char **expand_assignments(char **argv, int count)
2443{
2444 int i;
2445 char **p = NULL;
2446 /* Expand assignments into one string each */
2447 for (i = 0; i < count; i++) {
2448 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2449 }
2450 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002451}
2452
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002453
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002454#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002455/* never called */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002456void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002457
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002458static void reset_traps_to_defaults(void)
2459{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002460 /* This function is always called in a child shell
2461 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002462 * Child shells are not interactive.
2463 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2464 * Testcase: (while :; do :; done) + ^Z should background.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002465 * Same goes for SIGTERM, SIGHUP, SIGINT.
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002466 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002467 unsigned sig;
2468 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002469
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002470 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2471 return;
2472
2473 /* Stupid. It can be done with *single* &= op, but we can't use
2474 * the fact that G.blocked_set is implemented as a bitmask... */
2475 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2476 sig = 1;
2477 while (1) {
2478 if (mask & 1)
2479 sigdelset(&G.blocked_set, sig);
2480 mask >>= 1;
2481 if (!mask)
2482 break;
2483 sig++;
2484 }
2485
2486 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2487 mask = G.non_DFL_mask;
2488 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2489 if (!G.traps[sig])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002490 continue;
2491 free(G.traps[sig]);
2492 G.traps[sig] = NULL;
2493 /* There is no signal for 0 (EXIT) */
2494 if (sig == 0)
2495 continue;
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002496 /* There was a trap handler, we are removing it.
2497 * But if sig still has non-DFL handling,
2498 * we should not unblock it. */
2499 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002500 continue;
2501 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002502 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002503 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002504}
2505
2506#else /* !BB_MMU */
2507
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002508static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2509static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002510{
2511 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002512 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002513 struct variable *cur;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002514#if ENABLE_HUSH_FUNCTIONS
2515 struct function *funcp;
2516#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002517 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002518 unsigned cnt;
2519
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002520 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002521 argv = heredoc_argv;
2522 argv[0] = (char *) G.argv0_for_re_execing;
2523 argv[1] = (char *) "-<";
2524 argv[2] = (char *) s;
2525 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002526 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002527 goto do_exec;
2528 }
2529
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002530 sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002531 , (unsigned) G.root_pid
2532 , (unsigned) G.last_bg_pid
2533 , (unsigned) G.last_exitcode
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002534 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002535 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002536 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002537 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002538 */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002539 cnt = 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002540 for (cur = G.top_var; cur; cur = cur->next) {
2541 if (!cur->flg_export || cur->flg_read_only)
2542 cnt += 2;
2543 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002544#if ENABLE_HUSH_FUNCTIONS
2545 for (funcp = G.top_func; funcp; funcp = funcp->next)
2546 cnt += 3;
2547#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002548 pp = g_argv;
2549 while (*pp++)
2550 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002551 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002552 *pp++ = (char *) G.argv0_for_re_execing;
2553 *pp++ = param_buf;
2554 for (cur = G.top_var; cur; cur = cur->next) {
2555 if (cur->varstr == hush_version_str)
2556 continue;
2557 if (cur->flg_read_only) {
2558 *pp++ = (char *) "-R";
2559 *pp++ = cur->varstr;
2560 } else if (!cur->flg_export) {
2561 *pp++ = (char *) "-V";
2562 *pp++ = cur->varstr;
2563 }
2564 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002565#if ENABLE_HUSH_FUNCTIONS
2566 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2567 *pp++ = (char *) "-F";
2568 *pp++ = funcp->name;
2569 *pp++ = funcp->body_as_string;
2570 }
2571#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002572 /* We can pass activated traps here. Say, -Tnn:trap_string
2573 *
2574 * However, POSIX says that subshells reset signals with traps
2575 * to SIG_DFL.
2576 * I tested bash-3.2 and it not only does that with true subshells
2577 * of the form ( list ), but with any forked children shells.
2578 * I set trap "echo W" WINCH; and then tried:
2579 *
2580 * { echo 1; sleep 20; echo 2; } &
2581 * while true; do echo 1; sleep 20; echo 2; break; done &
2582 * true | { echo 1; sleep 20; echo 2; } | cat
2583 *
2584 * In all these cases sending SIGWINCH to the child shell
2585 * did not run the trap. If I add trap "echo V" WINCH;
2586 * _inside_ group (just before echo 1), it works.
2587 *
2588 * I conclude it means we don't need to pass active traps here.
2589 * exec syscall below resets them to SIG_DFL for us.
2590 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002591 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002592 *pp++ = (char *) s;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002593 *pp++ = g_argv0;
2594 while (*g_argv)
2595 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002596 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002597 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002598
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002599 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002600 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2601 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002602 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002603 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002604 if (argv[0][0] == '/')
2605 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002606 xfunc_error_retval = 127;
2607 bb_error_msg_and_die("can't re-execute the shell");
2608}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002609#endif /* !BB_MMU */
2610
2611
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002612static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002613{
2614 struct fd_pair pair;
2615 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002616 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002617 /* the _body_ of heredoc (misleading field name) */
2618 const char *heredoc = redir->rd_filename;
2619 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002620#if !BB_MMU
2621 char **to_free;
2622#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002623
2624 expanded = NULL;
2625 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2626 expanded = expand_pseudo_dquoted(heredoc);
2627 if (expanded)
2628 heredoc = expanded;
2629 }
2630 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002631
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002632 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002633 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002634 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002635
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002636 /* Try writing without forking. Newer kernels have
2637 * dynamically growing pipes. Must use non-blocking write! */
2638 ndelay_on(pair.wr);
2639 while (1) {
2640 written = write(pair.wr, heredoc, len);
2641 if (written <= 0)
2642 break;
2643 len -= written;
2644 if (len == 0) {
2645 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002646 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002647 return;
2648 }
2649 heredoc += written;
2650 }
2651 ndelay_off(pair.wr);
2652
2653 /* Okay, pipe buffer was not big enough */
2654 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002655 * for the unsuspecting parent process. Child creates a grandchild
2656 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002657 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002658#if !BB_MMU
2659 to_free = NULL;
2660#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002661 pid = vfork();
2662 if (pid < 0)
2663 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002664 if (pid == 0) {
2665 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002666 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002667 pid = BB_MMU ? fork() : vfork();
2668 if (pid < 0)
2669 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2670 if (pid != 0)
2671 _exit(0);
2672 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002673 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002674#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002675 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002676 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002677#else
2678 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002679 xmove_fd(pair.wr, STDOUT_FILENO);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002680 re_execute_shell(&to_free, heredoc, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002681#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002682 }
2683 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02002684#if ENABLE_HUSH_FAST
2685 G.count_SIGCHLD++;
2686//bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
2687#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002688 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002689#if !BB_MMU
2690 free(to_free);
2691#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002692 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002693 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002694 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002695}
2696
Eric Andersen25f27032001-04-26 23:22:31 +00002697/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2698 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002699static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002700{
2701 int openfd, mode;
2702 struct redir_struct *redir;
2703
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002704 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002705 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002706 /* rd_fd<<HERE case */
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002707 if (squirrel && redir->rd_fd < 3
2708 && squirrel[redir->rd_fd] < 0
2709 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002710 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002711 }
2712 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2713 * of the heredoc */
2714 debug_printf_parse("set heredoc '%s'\n",
2715 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002716 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002717 continue;
2718 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002719
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002720 if (redir->rd_dup == REDIRFD_TO_FILE) {
2721 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002722 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002723 if (redir->rd_filename == NULL) {
2724 /* Something went wrong in the parse.
2725 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002726 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002727 continue;
2728 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002729 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002730 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002731 openfd = open_or_warn(p, mode);
2732 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002733 if (openfd < 0) {
2734 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002735 * bash and ash both lose it as well (though zsh doesn't!) */
2736//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002737 return 1;
2738 }
2739 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002740 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002741 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002742 }
2743
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002744 if (openfd != redir->rd_fd) {
Denys Vlasenko1dd6cf82009-05-02 14:17:31 +02002745 if (squirrel && redir->rd_fd < 3
2746 && squirrel[redir->rd_fd] < 0
2747 ) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002748 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002749 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002750 if (openfd == REDIRFD_CLOSE) {
2751 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002752 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002753 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002754 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002755 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002756 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002757 }
Eric Andersen25f27032001-04-26 23:22:31 +00002758 }
2759 }
2760 return 0;
2761}
2762
2763static void restore_redirects(int squirrel[])
2764{
2765 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002766 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002767 fd = squirrel[i];
2768 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002769 /* We simply die on error */
2770 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002771 }
2772 }
2773}
2774
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002775
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002776static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002777
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002778/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002779static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002780{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002781 char **p;
2782 struct command *command;
2783 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002784 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002785
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002786 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002787 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002788 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789 for (i = 0; i < pi->num_cmds; i++) {
2790 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002791 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002792 if (command->argv) {
2793 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002794 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002795 }
2796 free_strings(command->argv);
2797 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002798 }
2799 /* not "else if": on syntax error, we may have both! */
2800 if (command->group) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002801 debug_printf_clean(" begin group (grp_type:%d)\n",
2802 command->grp_type);
2803 free_pipe_list(command->group);
2804 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002805 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002806 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002807 /* else is crucial here.
2808 * If group != NULL, child_func is meaningless */
2809#if ENABLE_HUSH_FUNCTIONS
2810 else if (command->child_func) {
2811 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2812 command->child_func->parent_cmd = NULL;
2813 }
2814#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002815#if !BB_MMU
2816 free(command->group_as_string);
2817 command->group_as_string = NULL;
2818#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002819 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002820 debug_printf_clean(" redirect %d%s",
2821 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002822 /* guard against the case >$FOO, where foo is unset or blank */
2823 if (r->rd_filename) {
2824 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2825 free(r->rd_filename);
2826 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002827 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002828 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002829 rnext = r->next;
2830 free(r);
2831 }
2832 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002833 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002834 free(pi->cmds); /* children are an array, they get freed all at once */
2835 pi->cmds = NULL;
2836#if ENABLE_HUSH_JOB
2837 free(pi->cmdtext);
2838 pi->cmdtext = NULL;
2839#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002840}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002841
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002842static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002843{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002844 struct pipe *pi, *next;
2845
2846 for (pi = head; pi; pi = next) {
2847#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002848 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002849#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002850 free_pipe(pi);
2851 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002852 next = pi->next;
2853 /*pi->next = NULL;*/
2854 free(pi);
2855 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002856}
2857
2858
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002859static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002860#if BB_MMU
2861#define parse_stream(pstring, input, end_trigger) \
2862 parse_stream(input, end_trigger)
2863#endif
2864static struct pipe *parse_stream(char **pstring,
2865 struct in_str *input,
2866 int end_trigger);
2867static void parse_and_run_string(const char *s);
2868
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002869
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002870static const struct built_in_command* find_builtin(const char *name)
2871{
2872 const struct built_in_command *x;
2873 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2874 if (strcmp(name, x->cmd) != 0)
2875 continue;
2876 debug_printf_exec("found builtin '%s'\n", name);
2877 return x;
2878 }
2879 return NULL;
2880}
2881
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002882#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002883static const struct function *find_function(const char *name)
2884{
2885 const struct function *funcp = G.top_func;
2886 while (funcp) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002887 if (strcmp(name, funcp->name) == 0) {
2888 break;
2889 }
2890 funcp = funcp->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002891 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002892 if (funcp)
2893 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002894 return funcp;
2895}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002896
Denis Vlasenkobc569742009-04-12 20:35:19 +00002897/* Note: takes ownership on name ptr */
2898static struct function *new_function(char *name)
2899{
2900 struct function *funcp;
2901 struct function **funcpp = &G.top_func;
2902
2903 while ((funcp = *funcpp) != NULL) {
2904 struct command *cmd;
2905
2906 if (strcmp(funcp->name, name) != 0) {
2907 funcpp = &funcp->next;
2908 continue;
2909 }
2910
2911 cmd = funcp->parent_cmd;
2912 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2913 if (!cmd) {
2914 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2915 free(funcp->name);
2916 /* Note: if !funcp->body, do not free body_as_string!
2917 * This is a special case of "-F name body" function:
2918 * body_as_string was not malloced! */
2919 if (funcp->body) {
2920 free_pipe_list(funcp->body);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002921# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00002922 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002923# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00002924 }
2925 } else {
2926 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2927 cmd->argv[0] = funcp->name;
2928 cmd->group = funcp->body;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002929# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00002930 cmd->group_as_string = funcp->body_as_string;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002931# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00002932 }
2933 goto skip;
2934 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002935 debug_printf_exec("remembering new function '%s'\n", name);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002936 funcp = *funcpp = xzalloc(sizeof(*funcp));
2937 /*funcp->next = NULL;*/
2938 skip:
2939 funcp->name = name;
2940 return funcp;
2941}
2942
Denis Vlasenko40e84372009-04-18 11:23:38 +00002943static void unset_func(const char *name)
2944{
2945 struct function *funcp;
2946 struct function **funcpp = &G.top_func;
2947
2948 while ((funcp = *funcpp) != NULL) {
2949 if (strcmp(funcp->name, name) == 0) {
2950 *funcpp = funcp->next;
root62452022009-05-04 12:00:19 +02002951 /* funcp is unlinked now, deleting it.
2952 * Note: if !funcp->body, the function was created by
2953 * "-F name body", do not free ->body_as_string
2954 * and ->name as they were not malloced. */
Denis Vlasenko40e84372009-04-18 11:23:38 +00002955 if (funcp->body) {
2956 free_pipe_list(funcp->body);
root62452022009-05-04 12:00:19 +02002957 free(funcp->name);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002958# if !BB_MMU
Denis Vlasenko40e84372009-04-18 11:23:38 +00002959 free(funcp->body_as_string);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002960# endif
Denis Vlasenko40e84372009-04-18 11:23:38 +00002961 }
2962 free(funcp);
2963 break;
2964 }
Denis Vlasenko73010672009-04-18 11:25:18 +00002965 funcpp = &funcp->next;
Denis Vlasenko40e84372009-04-18 11:23:38 +00002966 }
2967}
2968
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002969# if BB_MMU
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002970#define exec_function(nommu_save, funcp, argv) \
2971 exec_function(funcp, argv)
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02002972# endif
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002973static void exec_function(nommu_save_t *nommu_save,
2974 const struct function *funcp,
2975 char **argv) NORETURN;
2976static void exec_function(nommu_save_t *nommu_save,
2977 const struct function *funcp,
2978 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002979{
2980# if BB_MMU
2981 int n = 1;
2982
2983 argv[0] = G.global_argv[0];
2984 G.global_argv = argv;
2985 while (*++argv)
2986 n++;
2987 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002988 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002989 n = run_list(funcp->body);
2990 fflush(NULL);
2991 _exit(n);
2992# else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002993 re_execute_shell(&nommu_save->argv_from_re_execing,
2994 funcp->body_as_string,
2995 G.global_argv[0],
2996 argv + 1);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002997# endif
2998}
2999
3000static int run_function(const struct function *funcp, char **argv)
3001{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003002 int rc;
3003 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00003004 smallint sv_flg;
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003005
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003006 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003007 /* "we are in function, ok to use return" */
3008 sv_flg = G.flag_return_in_progress;
3009 G.flag_return_in_progress = -1;
3010
Denis Vlasenkobc569742009-04-12 20:35:19 +00003011 /* On MMU, funcp->body is always non-NULL */
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003012# if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00003013 if (!funcp->body) {
3014 /* Function defined by -F */
3015 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003016 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00003017 } else
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003018# endif
Denis Vlasenkobc569742009-04-12 20:35:19 +00003019 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003020 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00003021 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00003022
3023 G.flag_return_in_progress = sv_flg;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003024 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003025
Denis Vlasenko270b1c32009-04-17 18:54:50 +00003026 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003027}
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003028#endif /* ENABLE_HUSH_FUNCTIONS */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003029
3030
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003031#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003032#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
3033 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
3034#define pseudo_exec(nommu_save, command, argv_expanded) \
3035 pseudo_exec(command, argv_expanded)
3036#endif
3037
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003038/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00003039 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003040 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00003041 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003042 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003043static void pseudo_exec_argv(nommu_save_t *nommu_save,
3044 char **argv, int assignment_cnt,
3045 char **argv_expanded) NORETURN;
3046static void pseudo_exec_argv(nommu_save_t *nommu_save,
3047 char **argv, int assignment_cnt,
3048 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00003049{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003050 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003051
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003052 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003053 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00003054 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003055
Denis Vlasenko9504e442008-10-29 01:19:15 +00003056 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003057#if BB_MMU
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003058 set_vars_and_save_old(new_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003059 free(new_env); /* optional */
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003060 /* we can also destroy set_vars_and_save_old's return value,
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003061 * to save memory */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003062#else
3063 nommu_save->new_env = new_env;
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003064 nommu_save->old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003065#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003066 if (argv_expanded) {
3067 argv = argv_expanded;
3068 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003069 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003070#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003071 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003072#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003073 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003074
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003075#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3076 if (strchr(argv[0], '/') != NULL)
3077 goto skip;
3078#endif
3079
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003080 /* On NOMMU, we must never block!
3081 * Example: { sleep 99999 | read line } & echo Ok
3082 * read builtin will block on read syscall, leaving parent blocked
3083 * in vfork. Therefore we can't do this:
3084 */
3085#if BB_MMU
3086 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003087 * Depending on context, this might be redundant. But it's
3088 * easier to waste a few CPU cycles than it is to figure out
3089 * if this is one of those cases.
3090 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003091 {
3092 int rcode;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003093 const struct built_in_command *x = find_builtin(argv[0]);
3094 if (x) {
3095 rcode = x->function(argv);
3096 fflush(NULL);
3097 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00003098 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003099 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003100#endif
3101#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003102 /* Check if the command matches any functions */
3103 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003104 const struct function *funcp = find_function(argv[0]);
3105 if (funcp) {
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003106 exec_function(nommu_save, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003107 }
3108 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003109#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003110
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003111#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003112 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003113 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003114 int a = find_applet_by_name(argv[0]);
3115 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003116# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003117 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003118 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003119 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003120 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003121# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003122 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003123 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003124 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3125 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003126 /* If they called chroot or otherwise made the binary no longer
3127 * executable, fall through */
3128 }
3129 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003130#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003131
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003132#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003133 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003134#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003135 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003136 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003137 execvp(argv[0], argv);
Denis Vlasenkof9d4fc32009-04-21 20:40:51 +00003138 bb_perror_msg("can't execute '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00003139 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003140}
3141
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003142/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003143 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003144static void pseudo_exec(nommu_save_t *nommu_save,
3145 struct command *command,
3146 char **argv_expanded) NORETURN;
3147static void pseudo_exec(nommu_save_t *nommu_save,
3148 struct command *command,
3149 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003150{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003151 if (command->argv) {
3152 pseudo_exec_argv(nommu_save, command->argv,
3153 command->assignment_cnt, argv_expanded);
3154 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003155
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003156 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003157 /* Cases when we are here:
3158 * ( list )
3159 * { list } &
3160 * ... | ( list ) | ...
3161 * ... | { list } | ...
3162 */
3163#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003164 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003165 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003166 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003167 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003168 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003169 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003170 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003171#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003172 re_execute_shell(&nommu_save->argv_from_re_execing,
3173 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003174 G.global_argv[0],
3175 G.global_argv + 1);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003176#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003177 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003178
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003179 /* Case when we are here: ... | >file */
3180 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003181 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003182}
3183
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003184#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003185static const char *get_cmdtext(struct pipe *pi)
3186{
3187 char **argv;
3188 char *p;
3189 int len;
3190
3191 /* This is subtle. ->cmdtext is created only on first backgrounding.
3192 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003193 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003194 if (pi->cmdtext)
3195 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003196 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003197 if (!argv || !argv[0]) {
3198 pi->cmdtext = xzalloc(1);
3199 return pi->cmdtext;
3200 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003201
3202 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003203 do {
3204 len += strlen(*argv) + 1;
3205 } while (*++argv);
3206 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003207 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003208 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003209 do {
3210 len = strlen(*argv);
3211 memcpy(p, *argv, len);
3212 p += len;
3213 *p++ = ' ';
3214 } while (*++argv);
3215 p[-1] = '\0';
3216 return pi->cmdtext;
3217}
3218
Eric Andersenbafd94f2001-05-02 16:11:59 +00003219static void insert_bg_job(struct pipe *pi)
3220{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003221 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003222 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003223
3224 /* Linear search for the ID of the job to use */
3225 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003226 for (job = G.job_list; job; job = job->next)
3227 if (job->jobid >= pi->jobid)
3228 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003229
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003230 /* Add job to the list of running jobs */
3231 jobp = &G.job_list;
3232 while ((job = *jobp) != NULL)
3233 jobp = &job->next;
3234 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003235
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003236 *job = *pi; /* physical copy */
3237 job->next = NULL;
3238 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3239 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003240 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003241 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003242 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003243 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003244 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003245
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003246 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003247 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3248 /* Last command's pid goes to $! */
3249 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3250 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003251}
3252
Eric Andersenbafd94f2001-05-02 16:11:59 +00003253static void remove_bg_job(struct pipe *pi)
3254{
3255 struct pipe *prev_pipe;
3256
Denis Vlasenko87a86552008-07-29 19:43:10 +00003257 if (pi == G.job_list) {
3258 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003259 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003260 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003261 while (prev_pipe->next != pi)
3262 prev_pipe = prev_pipe->next;
3263 prev_pipe->next = pi->next;
3264 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003265 if (G.job_list)
3266 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003267 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003268 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003269}
Eric Andersen028b65b2001-06-28 01:10:11 +00003270
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003271/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003272static void delete_finished_bg_job(struct pipe *pi)
3273{
3274 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003275 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003276 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003277 free(pi);
3278}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003279#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003280
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003281/* Check to see if any processes have exited -- if they
3282 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003283static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003284{
Eric Andersenc798b072001-06-22 06:23:03 +00003285 int attributes;
3286 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003287#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003288 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003289#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003290 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003291 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003292
Denis Vlasenkod5762932009-03-31 11:22:57 +00003293 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3294
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003295 errno = 0;
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003296#if ENABLE_HUSH_FAST
3297 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
3298//bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d was 0?:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.last_waitpid_was_0);
3299 /* avoid doing syscall, nothing there anyway */
3300 if (G.last_waitpid_was_0)
3301 return 0;
3302 errno = ECHILD;
3303 return -1;
3304 }
3305#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003306
Eric Andersenc798b072001-06-22 06:23:03 +00003307 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003308 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003309 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003310
Denis Vlasenko1359da62007-04-21 23:27:30 +00003311/* Do we do this right?
3312 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003313 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003314 * [3]+ Stopped sleep 20 | false
3315 * bash-3.00# echo $?
3316 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003317 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003318 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003319 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003320 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003321 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003322 int dead;
3323
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003324#if ENABLE_HUSH_FAST
3325 i = G.count_SIGCHLD;
3326#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003327 childpid = waitpid(-1, &status, attributes);
3328 if (childpid <= 0) {
3329 if (childpid && errno != ECHILD)
3330 bb_perror_msg("waitpid");
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003331#if ENABLE_HUSH_FAST
3332 else { /* Until next SIGCHLD, waitpid's are useless */
3333 G.last_waitpid_was_0 = (childpid == 0);
3334 G.handled_SIGCHLD = i;
3335//bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3336 }
3337#endif
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003338 break;
3339 }
3340 dead = WIFEXITED(status) || WIFSIGNALED(status);
3341
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003342#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003343 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003344 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003345 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3346 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003347 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003348 childpid, WTERMSIG(status), WEXITSTATUS(status));
3349 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003350 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003351 childpid, WEXITSTATUS(status));
3352#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003353 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003354 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003355 for (i = 0; i < fg_pipe->num_cmds; i++) {
3356 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3357 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003358 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003359 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003360 fg_pipe->cmds[i].pid = 0;
3361 fg_pipe->alive_cmds--;
3362 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003363 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003364 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003365 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003366 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003367 /* bash prints killing signal's name for *last*
3368 * process in pipe (prints just newline for SIGINT).
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003369 * Mimic this. Example: "sleep 5" + ^\
Denis Vlasenko40e84372009-04-18 11:23:38 +00003370 */
3371 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003372 int sig = WTERMSIG(status);
3373 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003374 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003375 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003376 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003377 fg_pipe->cmds[i].is_stopped = 1;
3378 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003379 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003380 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3381 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3382 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003383 /* All processes in fg pipe have exited or stopped */
3384/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3385 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3386 * and "killall -STOP cat" */
3387 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003388#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003389 if (fg_pipe->alive_cmds)
3390 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003391#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003392 return rcode;
3393 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003394 }
3395 /* There are still running processes in the fg pipe */
3396 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003397 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003398 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003399 }
3400
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003401#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003402 /* We asked to wait for bg or orphaned children */
3403 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003404 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003405 for (i = 0; i < pi->num_cmds; i++) {
3406 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003407 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003408 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003409 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003410 /* Happens when shell is used as init process (init=/bin/sh) */
3411 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003412 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003413
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003414 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003415 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003416 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003417 pi->cmds[i].pid = 0;
3418 pi->alive_cmds--;
3419 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003420 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003421 printf(JOB_STATUS_FORMAT, pi->jobid,
3422 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003423 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003424 }
3425 } else {
3426 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003427 pi->cmds[i].is_stopped = 1;
3428 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003429 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003430#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003431 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003432
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003433 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003434}
3435
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003436#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003437static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3438{
3439 pid_t p;
3440 int rcode = checkjobs(fg_pipe);
Mike Frysinger38478a62009-05-20 04:48:06 -04003441 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003442 /* Job finished, move the shell to the foreground */
3443 p = getpgrp(); /* our process group id */
3444 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3445 tcsetpgrp(G_interactive_fd, p);
3446 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003447 return rcode;
3448}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003449#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003450
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003451/* Start all the jobs, but don't wait for anything to finish.
3452 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003453 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003454 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003455 * to finish to determine the exit status of the pipe. If the pipe
3456 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003457 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003458 * return value.
3459 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003460 * Returns -1 only if started some children. IOW: we have to
3461 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003462 *
3463 * The only case when we do not need to [v]fork is when the pipe
3464 * is single, non-backgrounded, non-subshell command. Examples:
3465 * cmd ; ... { list } ; ...
3466 * cmd && ... { list } && ...
3467 * cmd || ... { list } || ...
3468 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3469 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003470 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003471 *
3472 * Cases when we must fork:
3473 * non-single: cmd | cmd
3474 * backgrounded: cmd & { list } &
3475 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003476 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003477static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003478{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003479 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003480 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003481 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003482 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003483 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003484 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003485 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003486 /* it is not always needed, but we aim to smaller code */
3487 int squirrel[] = { -1, -1, -1 };
3488 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003489
Denis Vlasenko552433b2009-04-04 19:29:21 +00003490 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003491 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003492
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003493 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003494 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003495 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003496 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003497
Denis Vlasenko552433b2009-04-04 19:29:21 +00003498 if (pi->num_cmds != 1
3499 || pi->followup == PIPE_BG
3500 || command->grp_type == GRP_SUBSHELL
3501 ) {
3502 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003503 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003504
Denis Vlasenko552433b2009-04-04 19:29:21 +00003505 pi->alive_cmds = 1;
3506
3507 debug_printf_exec(": group:%p argv:'%s'\n",
3508 command->group, command->argv ? command->argv[0] : "NONE");
3509
3510 if (command->group) {
3511#if ENABLE_HUSH_FUNCTIONS
3512 if (command->grp_type == GRP_FUNCTION) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003513 /* "executing" func () { list } */
3514 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003515
Denis Vlasenkobc569742009-04-12 20:35:19 +00003516 funcp = new_function(command->argv[0]);
3517 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003518 funcp->body = command->group;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003519# if !BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003520 funcp->body_as_string = command->group_as_string;
3521 command->group_as_string = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003522# endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003523 command->group = NULL;
3524 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003525 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3526 funcp->parent_cmd = command;
3527 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003528
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003529 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3530 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003531 return EXIT_SUCCESS;
3532 }
3533#endif
3534 /* { list } */
3535 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003536 rcode = 1; /* exitcode if redir failed */
3537 if (setup_redirects(command, squirrel) == 0) {
3538 debug_printf_exec(": run_list\n");
3539 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003540 }
Eric Andersen04407e52001-06-07 16:42:05 +00003541 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003542 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003543 debug_leave();
3544 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003545 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003546 }
3547
Denis Vlasenko552433b2009-04-04 19:29:21 +00003548 argv = command->argv ? command->argv : (char **) &null_ptr;
3549 {
3550 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003551#if ENABLE_HUSH_FUNCTIONS
3552 const struct function *funcp;
3553#else
3554 enum { funcp = 0 };
3555#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003556 char **new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003557 struct variable *old_vars = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003558
Denis Vlasenko552433b2009-04-04 19:29:21 +00003559 if (argv[command->assignment_cnt] == NULL) {
3560 /* Assignments, but no command */
3561 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003562 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003563 restore_redirects(squirrel);
3564 /* Set shell variables */
3565 while (*argv) {
3566 p = expand_string_to_string(*argv);
3567 debug_printf_exec("set shell var:'%s'->'%s'\n",
3568 *argv, p);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003569 set_local_var(p, 0, 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003570 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003571 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003572 /* Do we need to flag set_local_var() errors?
3573 * "assignment to readonly var" and "putenv error"
3574 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003575 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003576 debug_leave();
3577 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003578 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003579 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003580
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003581 /* Expand the rest into (possibly) many strings each */
Denis Vlasenko552433b2009-04-04 19:29:21 +00003582 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003583
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003584 x = find_builtin(argv_expanded[0]);
3585#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003586 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003587 if (!x)
3588 funcp = find_function(argv_expanded[0]);
3589#endif
3590 if (x || funcp) {
3591 if (!funcp) {
3592 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3593 debug_printf("exec with redirects only\n");
3594 rcode = setup_redirects(command, NULL);
3595 goto clean_up_and_ret1;
3596 }
Eric Andersen25f27032001-04-26 23:22:31 +00003597 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003598 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003599 * This is perfect for work that comes after exec().
3600 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003601 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003602 rcode = setup_redirects(command, squirrel);
3603 if (rcode == 0) {
3604 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003605 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003606 if (!funcp) {
3607 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003608 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003609 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003610 fflush(NULL);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003611 }
3612#if ENABLE_HUSH_FUNCTIONS
3613 else {
3614 debug_printf_exec(": function '%s' '%s'...\n",
3615 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003616 rcode = run_function(funcp, argv_expanded) & 0xff;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003617 }
3618#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003619 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003620#if ENABLE_FEATURE_SH_STANDALONE
3621 clean_up_and_ret:
3622#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003623 restore_redirects(squirrel);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003624 unset_vars(new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003625 add_vars(old_vars);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003626 clean_up_and_ret1:
3627 free(argv_expanded);
3628 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003629 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003630 debug_printf_exec("run_pipe return %d\n", rcode);
3631 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003632 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003633
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003634#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003635 i = find_applet_by_name(argv_expanded[0]);
3636 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003637 rcode = setup_redirects(command, squirrel);
3638 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003639 new_env = expand_assignments(argv, command->assignment_cnt);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003640 old_vars = set_vars_and_save_old(new_env);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003641 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003642 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003643 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003644 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003645 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003646 }
3647#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003648 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003649 }
3650
Denis Vlasenko552433b2009-04-04 19:29:21 +00003651 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003652 /* NB: argv_expanded may already be created, and that
3653 * might include `cmd` runs! Do not rerun it! We *must*
3654 * use argv_expanded if it's non-NULL */
3655
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003656 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003657 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003658 nextin = 0;
3659
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003660 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003661 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003662#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003663 volatile nommu_save_t nommu_save;
3664 nommu_save.new_env = NULL;
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003665 nommu_save.old_vars = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003666 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003667 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003668#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003669 command = &(pi->cmds[i]);
3670 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003671 debug_printf_exec(": pipe member '%s' '%s'...\n",
3672 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003673 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003674 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003675 }
Eric Andersen25f27032001-04-26 23:22:31 +00003676
3677 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003678 pipefds.rd = 0;
3679 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003680 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003681 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003682
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003683 command->pid = BB_MMU ? fork() : vfork();
3684 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003685#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003686 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003687
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003688 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003689 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003690 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003691 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003692 pgrp = pi->pgrp;
3693 if (pgrp < 0) /* true for 1st process only */
3694 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003695 if (setpgid(0, pgrp) == 0
3696 && pi->followup != PIPE_BG
Mike Frysinger38478a62009-05-20 04:48:06 -04003697 && G_saved_tty_pgrp /* we have ctty */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003698 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003699 /* We do it in *every* child, not just first,
3700 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003701 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003702 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003703 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003704#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003705 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3706 /* 1st cmd in backgrounded pipe
3707 * should have its stdin /dev/null'ed */
3708 close(0);
3709 if (open(bb_dev_null, O_RDONLY))
3710 xopen("/", O_RDONLY);
3711 } else {
3712 xmove_fd(nextin, 0);
3713 }
3714 xmove_fd(pipefds.wr, 1);
3715 if (pipefds.rd > 1)
3716 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00003717 /* Like bash, explicit redirects override pipes,
3718 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003719 if (setup_redirects(command, NULL))
3720 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00003721
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003722 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003723 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3724
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003725 /* Stores to nommu_save list of env vars putenv'ed
3726 * (NOMMU, on MMU we don't need that) */
3727 /* cast away volatility... */
3728 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003729 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00003730 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003731
Denis Vlasenkof9375282009-04-05 19:13:39 +00003732 /* parent or error */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02003733#if ENABLE_HUSH_FAST
3734 G.count_SIGCHLD++;
3735//bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
3736#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003737 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003738#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003739 /* Clean up after vforked child */
3740 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003741 free(nommu_save.argv_from_re_execing);
Denys Vlasenkoacdc49c2009-05-04 01:58:10 +02003742 unset_vars(nommu_save.new_env);
Denys Vlasenkocb6ff252009-05-04 00:14:30 +02003743 add_vars(nommu_save.old_vars);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003744#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003745 free(argv_expanded);
3746 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003747 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003748 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003749 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003750 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003751 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003752#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003753 /* Second and next children need to know pid of first one */
3754 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003755 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003756#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003757 }
Eric Andersen25f27032001-04-26 23:22:31 +00003758
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003759 if (i)
3760 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003761 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003762 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003763 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003764 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00003765 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003766
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003767 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003768 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00003769 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3770 return 1;
3771 }
3772
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003773 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003774 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003775 return -1;
3776}
3777
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003778#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003779static void debug_print_tree(struct pipe *pi, int lvl)
3780{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003781 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003782 [PIPE_SEQ] = "SEQ",
3783 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003784 [PIPE_OR ] = "OR" ,
3785 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003786 };
3787 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003788 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003789#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003790 [RES_IF ] = "IF" ,
3791 [RES_THEN ] = "THEN" ,
3792 [RES_ELIF ] = "ELIF" ,
3793 [RES_ELSE ] = "ELSE" ,
3794 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003795#endif
3796#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003797 [RES_FOR ] = "FOR" ,
3798 [RES_WHILE] = "WHILE",
3799 [RES_UNTIL] = "UNTIL",
3800 [RES_DO ] = "DO" ,
3801 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003802#endif
3803#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003804 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003805#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003806#if ENABLE_HUSH_CASE
3807 [RES_CASE ] = "CASE" ,
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003808 [RES_CASE_IN ] = "CASE_IN" ,
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003809 [RES_MATCH] = "MATCH",
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02003810 [RES_CASE_BODY] = "CASE_BODY",
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003811 [RES_ESAC ] = "ESAC" ,
3812#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00003813 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003814 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003815 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003816 static const char *const GRPTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003817 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00003818 "()",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003819#if ENABLE_HUSH_FUNCTIONS
3820 "func()",
3821#endif
3822 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003823
3824 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003825
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003826 pin = 0;
3827 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003828 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3829 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003830 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003831 while (prn < pi->num_cmds) {
3832 struct command *command = &pi->cmds[prn];
3833 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003834
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003835 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003836 lvl*2, "", prn,
3837 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003838 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003839 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003840 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003841 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003842 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003843 prn++;
3844 continue;
3845 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003846 if (argv) while (*argv) {
3847 fprintf(stderr, " '%s'", *argv);
3848 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003849 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003850 fprintf(stderr, "\n");
3851 prn++;
3852 }
3853 pi = pi->next;
3854 pin++;
3855 }
3856}
3857#endif
3858
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003859/* NB: called by pseudo_exec, and therefore must not modify any
3860 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003861static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003862{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003863#if ENABLE_HUSH_CASE
3864 char *case_word = NULL;
3865#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003866#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003867 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003868 char *for_varname = NULL;
3869 char **for_lcur = NULL;
3870 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00003871#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003872 smallint last_followup;
3873 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003874#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003875 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003876#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003877 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003878#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00003879#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003880 smallint rword; /* enum reserved_style */
3881 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003882#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003883
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003884 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003885 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003886
Denis Vlasenko06810332007-05-21 23:30:54 +00003887#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003888 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003889 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3890 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003891 continue;
3892 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003893 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003894 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003895 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003896 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003897 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003898 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003899 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003900 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003901 continue;
3902 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003903 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3904 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003905 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003906 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003907 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003908 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003909 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003910 }
3911 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003912#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003913
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003914 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00003915 * in order to return, no direct "return" statements please.
3916 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003917
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003918#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003919 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003920#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003921
Denis Vlasenko0e151382009-04-06 18:40:31 +00003922#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003923 rword = RES_NONE;
3924 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003925#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003926 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003927 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003928
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003929 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003930 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00003931 if (G.flag_SIGINT)
3932 break;
3933
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003934 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003935 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3936 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00003937#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00003938 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003939 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00003940 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003941 /* start of a loop: remember where loop starts */
3942 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003943 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003944 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003945#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003946 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003947 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003948 if ((rcode == 0 && last_followup == PIPE_OR)
3949 || (rcode != 0 && last_followup == PIPE_AND)
3950 ) {
3951 /* It is "<true> || CMD" or "<false> && CMD"
3952 * and we should not execute CMD */
3953 debug_printf_exec("skipped cmd because of || or &&\n");
3954 last_followup = pi->followup;
3955 continue;
3956 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003957 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003958 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003959 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00003960#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003961 if (cond_code) {
3962 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00003963 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003964 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003965 /* "if <false> THEN cmd": skip cmd */
3966 continue;
3967 }
3968 } else {
3969 if (rword == RES_ELSE || rword == RES_ELIF) {
3970 /* "if <true> then ... ELSE/ELIF cmd":
3971 * skip cmd and all following ones */
3972 break;
3973 }
3974 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003975#endif
3976#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003977 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003978 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003979 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003980
3981 static const char encoded_dollar_at[] ALIGN1 = {
3982 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3983 }; /* encoded representation of "$@" */
3984 static const char *const encoded_dollar_at_argv[] = {
3985 encoded_dollar_at, NULL
3986 }; /* argv list with one element: "$@" */
3987 char **vals;
3988
3989 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003990 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003991 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003992 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003993 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003994 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003995 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003996 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003997 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003998 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003999 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00004000 debug_print_strings("for_list made from", vals);
4001 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004002 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004003 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004004 for_varname = pi->cmds[0].argv[0];
4005 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004006 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004007 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004008 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00004009 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004010 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004011 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00004012 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004013 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004014 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004015 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004016 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004017 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004018 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
4019 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004020 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004021 if (rword == RES_IN) {
4022 continue; /* "for v IN list;..." - "in" has no cmds anyway */
4023 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004024 if (rword == RES_DONE) {
4025 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004026 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004027#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004028#if ENABLE_HUSH_CASE
4029 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004030 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004031 continue;
4032 }
4033 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004034 char **argv;
4035
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004036 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
4037 break;
4038 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004039 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004040 while (*argv) {
4041 char *pattern = expand_string_to_string(*argv);
4042 /* TODO: which FNM_xxx flags to use? */
4043 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
4044 free(pattern);
4045 if (cond_code == 0) { /* match! we will execute this branch */
4046 free(case_word); /* make future "word)" stop */
4047 case_word = NULL;
4048 break;
4049 }
4050 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004051 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004052 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004053 }
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004054 if (rword == RES_CASE_BODY) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004055 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004056 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004057 }
4058#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00004059 /* Just pressing <enter> in shell should check for jobs.
4060 * OTOH, in non-interactive shell this is useless
4061 * and only leads to extra job checks */
4062 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004063 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004064 goto check_jobs_and_continue;
4065 continue;
4066 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004067
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004068 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00004069 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004070 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004071 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004072 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004073 {
4074 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004075#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004076 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004077#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004078 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4079 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004080 /* We ran a builtin, function, or group.
4081 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004082 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004083 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004084 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004085 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004086#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004087 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004088 if (G.flag_break_continue) {
4089 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004090 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004091 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004092 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004093 G.depth_break_continue--;
4094 if (G.depth_break_continue == 0)
4095 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004096 /* else: e.g. "continue 2" should *break* once, *then* continue */
4097 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004098 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004099 goto check_jobs_and_break;
4100 /* "continue": simulate end of loop */
4101 rword = RES_DONE;
4102 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004103 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004104#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004105#if ENABLE_HUSH_FUNCTIONS
4106 if (G.flag_return_in_progress == 1)
4107 goto check_jobs_and_break;
4108#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004109 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004110 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004111 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004112 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4113 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004114 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004115#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004116 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004117 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004118#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004119 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004120 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004121 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004122#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004123 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004124 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004125 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004126 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004127 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004128 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004129#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004130 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004131 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004132 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004133 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004134 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004135 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004136 }
4137 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004138
4139 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004140#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004141 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004142 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004143#endif
4144#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004145 /* Beware of "while false; true; do ..."! */
4146 if (pi->next && pi->next->res_word == RES_DO) {
4147 if (rword == RES_WHILE) {
4148 if (rcode) {
4149 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004150 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004151 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4152 goto check_jobs_and_break;
4153 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004154 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004155 if (rword == RES_UNTIL) {
4156 if (!rcode) {
4157 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004158 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004159 checkjobs(NULL);
4160 break;
4161 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004162 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004163 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004164#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004165
4166 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004167 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004168 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004169
4170#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004171 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004172#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004173#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004174 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004175 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004176 free(for_list);
4177#endif
4178#if ENABLE_HUSH_CASE
4179 free(case_word);
4180#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004181 debug_leave();
4182 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004183 return rcode;
4184}
4185
Eric Andersen25f27032001-04-26 23:22:31 +00004186/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004187static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004188{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004189 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004190 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004191 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004192 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004193 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004194 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004195 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004196 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004197 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004198 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004199 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004200 return rcode;
4201}
4202
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004203
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004204static struct pipe *new_pipe(void)
4205{
Eric Andersen25f27032001-04-26 23:22:31 +00004206 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004207 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004208 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004209 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004210 return pi;
4211}
4212
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004213/* Command (member of a pipe) is complete, or we start a new pipe
4214 * if ctx->command is NULL.
4215 * No errors possible here.
4216 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004217static int done_command(struct parse_context *ctx)
4218{
4219 /* The command is really already in the pipe structure, so
4220 * advance the pipe counter and make a new, null command. */
4221 struct pipe *pi = ctx->pipe;
4222 struct command *command = ctx->command;
4223
4224 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004225 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004226 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004227 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004228 }
4229 pi->num_cmds++;
4230 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004231 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004232 } else {
4233 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4234 }
4235
4236 /* Only real trickiness here is that the uncommitted
4237 * command structure is not counted in pi->num_cmds. */
4238 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004239 ctx->command = command = &pi->cmds[pi->num_cmds];
4240 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004241 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004242 return pi->num_cmds; /* used only for 0/nonzero check */
4243}
4244
4245static void done_pipe(struct parse_context *ctx, pipe_style type)
4246{
4247 int not_null;
4248
4249 debug_printf_parse("done_pipe entered, followup %d\n", type);
4250 /* Close previous command */
4251 not_null = done_command(ctx);
4252 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004253#if HAS_KEYWORDS
4254 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4255 ctx->ctx_inverted = 0;
4256 ctx->pipe->res_word = ctx->ctx_res_w;
4257#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004258
4259 /* Without this check, even just <enter> on command line generates
4260 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004261 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004262 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004263#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004264 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004265#endif
4266#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004267 || ctx->ctx_res_w == RES_DONE
4268 || ctx->ctx_res_w == RES_FOR
4269 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004270#endif
4271#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004272 || ctx->ctx_res_w == RES_ESAC
4273#endif
4274 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004275 struct pipe *new_p;
4276 debug_printf_parse("done_pipe: adding new pipe: "
4277 "not_null:%d ctx->ctx_res_w:%d\n",
4278 not_null, ctx->ctx_res_w);
4279 new_p = new_pipe();
4280 ctx->pipe->next = new_p;
4281 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004282 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004283 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004284 * This is used to control execution.
4285 * RES_FOR and RES_IN are NOT sticky (needed to support
4286 * cases where variable or value happens to match a keyword):
4287 */
4288#if ENABLE_HUSH_LOOPS
4289 if (ctx->ctx_res_w == RES_FOR
4290 || ctx->ctx_res_w == RES_IN)
4291 ctx->ctx_res_w = RES_NONE;
4292#endif
4293#if ENABLE_HUSH_CASE
4294 if (ctx->ctx_res_w == RES_MATCH)
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004295 ctx->ctx_res_w = RES_CASE_BODY;
4296 if (ctx->ctx_res_w == RES_CASE)
4297 ctx->ctx_res_w = RES_CASE_IN;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004298#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004299 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004300 /* Create the memory for command, roughly:
4301 * ctx->pipe->cmds = new struct command;
4302 * ctx->command = &ctx->pipe->cmds[0];
4303 */
4304 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004305 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004306 }
4307 debug_printf_parse("done_pipe return\n");
4308}
4309
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004310static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004311{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004312 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004313 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004314 /* Create the memory for command, roughly:
4315 * ctx->pipe->cmds = new struct command;
4316 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004317 */
4318 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004319}
4320
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004321/* If a reserved word is found and processed, parse context is modified
4322 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004323 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004324#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004325struct reserved_combo {
4326 char literal[6];
4327 unsigned char res;
4328 unsigned char assignment_flag;
4329 int flag;
4330};
4331enum {
4332 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004333#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004334 FLAG_IF = (1 << RES_IF ),
4335 FLAG_THEN = (1 << RES_THEN ),
4336 FLAG_ELIF = (1 << RES_ELIF ),
4337 FLAG_ELSE = (1 << RES_ELSE ),
4338 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004339#endif
4340#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004341 FLAG_FOR = (1 << RES_FOR ),
4342 FLAG_WHILE = (1 << RES_WHILE),
4343 FLAG_UNTIL = (1 << RES_UNTIL),
4344 FLAG_DO = (1 << RES_DO ),
4345 FLAG_DONE = (1 << RES_DONE ),
4346 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004347#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004348#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004349 FLAG_MATCH = (1 << RES_MATCH),
4350 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004351#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004352 FLAG_START = (1 << RES_XXXX ),
4353};
4354
4355static const struct reserved_combo* match_reserved_word(o_string *word)
4356{
Eric Andersen25f27032001-04-26 23:22:31 +00004357 /* Mostly a list of accepted follow-up reserved words.
4358 * FLAG_END means we are done with the sequence, and are ready
4359 * to turn the compound list into a command.
4360 * FLAG_START means the word must start a new compound list.
4361 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004362 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004363#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004364 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4365 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4366 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4367 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4368 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4369 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004370#endif
4371#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004372 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4373 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4374 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4375 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4376 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4377 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004378#endif
4379#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004380 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4381 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004382#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004383 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004384 const struct reserved_combo *r;
4385
4386 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4387 if (strcmp(word->data, r->literal) == 0)
4388 return r;
4389 }
4390 return NULL;
4391}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004392/* Return 0: not a keyword, 1: keyword
4393 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004394static int reserved_word(o_string *word, struct parse_context *ctx)
4395{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004396#if ENABLE_HUSH_CASE
4397 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004398 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004399 };
4400#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004401 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004402
Denis Vlasenkobb929512009-04-16 10:59:40 +00004403 if (word->o_quoted)
4404 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004405 r = match_reserved_word(word);
4406 if (!r)
4407 return 0;
4408
4409 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004410#if ENABLE_HUSH_CASE
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004411 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
4412 /* "case word IN ..." - IN part starts first MATCH part */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004413 r = &reserved_match;
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004414 } else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004415#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004416 if (r->flag == 0) { /* '!' */
4417 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004418 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004419 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004420 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004421 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004422 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004423 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004424 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004425 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004426
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004427 old = xmalloc(sizeof(*old));
4428 debug_printf_parse("push stack %p\n", old);
4429 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004430 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004431 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004432 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004433 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004434 ctx->ctx_res_w = RES_SNTX;
4435 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004436 } else {
4437 /* "{...} fi" is ok. "{...} if" is not
4438 * Example:
4439 * if { echo foo; } then { echo bar; } fi */
4440 if (ctx->command->group)
4441 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004442 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004443
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004444 ctx->ctx_res_w = r->res;
4445 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004446 word->o_assignment = r->assignment_flag;
4447
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004448 if (ctx->old_flag & FLAG_END) {
4449 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004450
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004451 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004452 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004453 old = ctx->stack;
4454 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004455 old->command->grp_type = GRP_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004456#if !BB_MMU
4457 o_addstr(&old->as_string, ctx->as_string.data);
4458 o_free_unsafe(&ctx->as_string);
4459 old->command->group_as_string = xstrdup(old->as_string.data);
4460 debug_printf_parse("pop, remembering as:'%s'\n",
4461 old->command->group_as_string);
4462#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004463 *ctx = *old; /* physical copy */
4464 free(old);
4465 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004466 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004467}
Denis Vlasenko06810332007-05-21 23:30:54 +00004468#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004469
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004470/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004471 * Normal return is 0. Syntax errors return 1.
4472 * Note: on return, word is reset, but not o_free'd!
4473 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004474static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004475{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004476 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004477
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004478 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004479 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004480 debug_printf_parse("done_word return 0: true null, ignored\n");
4481 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004482 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004483
Eric Andersen25f27032001-04-26 23:22:31 +00004484 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004485 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4486 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004487 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4488 * "2.7 Redirection
4489 * ...the word that follows the redirection operator
4490 * shall be subjected to tilde expansion, parameter expansion,
4491 * command substitution, arithmetic expansion, and quote
4492 * removal. Pathname expansion shall not be performed
4493 * on the word by a non-interactive shell; an interactive
4494 * shell may perform it, but shall do so only when
4495 * the expansion would result in one word."
4496 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004497 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004498 /* Cater for >\file case:
4499 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4500 * Same with heredocs:
4501 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4502 */
4503 unbackslash(ctx->pending_redirect->rd_filename);
4504 /* Is it <<"HEREDOC"? */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004505 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4506 && word->o_quoted
4507 ) {
4508 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4509 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004510 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004511 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004512 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004513 /* If this word wasn't an assignment, next ones definitely
4514 * can't be assignments. Even if they look like ones. */
4515 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4516 && word->o_assignment != WORD_IS_KEYWORD
4517 ) {
4518 word->o_assignment = NOT_ASSIGNMENT;
4519 } else {
4520 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4521 command->assignment_cnt++;
4522 word->o_assignment = MAYBE_ASSIGNMENT;
4523 }
4524
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004525#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004526# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004527 if (ctx->ctx_dsemicolon
4528 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4529 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004530 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004531 /* ctx->ctx_res_w = RES_MATCH; */
4532 ctx->ctx_dsemicolon = 0;
4533 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004534# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004535 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004536# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004537 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4538 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004539# endif
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02004540# if ENABLE_HUSH_CASE
4541 && ctx->ctx_res_w != RES_CASE
4542# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004543 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004544 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004545 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004546 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004547 debug_printf_parse("done_word return %d\n",
4548 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004549 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004550 }
Eric Andersen25f27032001-04-26 23:22:31 +00004551 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004552#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004553 if (command->group) {
4554 /* "{ echo foo; } echo bar" - bad */
4555 syntax_error_at(word->data);
4556 debug_printf_parse("done_word return 1: syntax error, "
4557 "groups and arglists don't mix\n");
4558 return 1;
4559 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004560 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004561 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4562 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004563 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004564 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004565 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004566 char *p = word->data;
4567 while (p[0] == SPECIAL_VAR_SYMBOL
4568 && (p[1] & 0x7f) == '@'
4569 && p[2] == SPECIAL_VAR_SYMBOL
4570 ) {
4571 p += 3;
4572 }
4573 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004574 /* saw no "$@", or not only "$@" but some
4575 * real text is there too */
4576 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004577 * e.g. "", $empty"" etc to not disappear */
4578 o_addchr(word, SPECIAL_VAR_SYMBOL);
4579 o_addchr(word, SPECIAL_VAR_SYMBOL);
4580 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004581 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004582 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004583 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004584 }
Eric Andersen25f27032001-04-26 23:22:31 +00004585
Denis Vlasenko06810332007-05-21 23:30:54 +00004586#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004587 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004588 if (word->o_quoted
4589 || !is_well_formed_var_name(command->argv[0], '\0')
4590 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004591 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004592 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004593 return 1;
4594 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004595 /* Force FOR to have just one word (variable name) */
4596 /* NB: basically, this makes hush see "for v in ..."
4597 * syntax as if it is "for v; in ...". FOR and IN become
4598 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004599 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004600 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004601#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004602#if ENABLE_HUSH_CASE
4603 /* Force CASE to have just one word */
4604 if (ctx->ctx_res_w == RES_CASE) {
4605 done_pipe(ctx, PIPE_SEQ);
4606 }
4607#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004608
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004609 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004610
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004611 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004612 return 0;
4613}
4614
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004615
4616/* Peek ahead in the input to find out if we have a "&n" construct,
4617 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004618 * Return:
4619 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4620 * REDIRFD_SYNTAX_ERR if syntax error,
4621 * REDIRFD_TO_FILE if no & was seen,
4622 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004623 */
4624#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004625#define parse_redir_right_fd(as_string, input) \
4626 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004627#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004628static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004629{
4630 int ch, d, ok;
4631
4632 ch = i_peek(input);
4633 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004634 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004635
4636 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004637 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004638 ch = i_peek(input);
4639 if (ch == '-') {
4640 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004641 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004642 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004643 }
4644 d = 0;
4645 ok = 0;
4646 while (ch != EOF && isdigit(ch)) {
4647 d = d*10 + (ch-'0');
4648 ok = 1;
4649 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004650 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004651 ch = i_peek(input);
4652 }
4653 if (ok) return d;
4654
4655//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4656
4657 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004658 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004659}
4660
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004661/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004662 */
4663static int parse_redirect(struct parse_context *ctx,
4664 int fd,
4665 redir_type style,
4666 struct in_str *input)
4667{
4668 struct command *command = ctx->command;
4669 struct redir_struct *redir;
4670 struct redir_struct **redirp;
4671 int dup_num;
4672
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004673 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004674 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004675 /* Check for a '>&1' type redirect */
4676 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4677 if (dup_num == REDIRFD_SYNTAX_ERR)
4678 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004679 } else {
4680 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004681 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004682 if (dup_num) { /* <<-... */
4683 ch = i_getch(input);
4684 nommu_addchr(&ctx->as_string, ch);
4685 ch = i_peek(input);
4686 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004687 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004688
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004689 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004690 int ch = i_peek(input);
4691 if (ch == '|') {
4692 /* >|FILE redirect ("clobbering" >).
4693 * Since we do not support "set -o noclobber" yet,
4694 * >| and > are the same for now. Just eat |.
4695 */
4696 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004697 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004698 }
4699 }
4700
4701 /* Create a new redir_struct and append it to the linked list */
4702 redirp = &command->redirects;
4703 while ((redir = *redirp) != NULL) {
4704 redirp = &(redir->next);
4705 }
4706 *redirp = redir = xzalloc(sizeof(*redir));
4707 /* redir->next = NULL; */
4708 /* redir->rd_filename = NULL; */
4709 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004710 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004711
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004712 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4713 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004714
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004715 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004716 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004717 /* Erik had a check here that the file descriptor in question
4718 * is legit; I postpone that to "run time"
4719 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004720 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4721 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004722 } else {
4723 /* Set ctx->pending_redirect, so we know what to do at the
4724 * end of the next parsed word. */
4725 ctx->pending_redirect = redir;
4726 }
4727 return 0;
4728}
4729
Eric Andersen25f27032001-04-26 23:22:31 +00004730/* If a redirect is immediately preceded by a number, that number is
4731 * supposed to tell which file descriptor to redirect. This routine
4732 * looks for such preceding numbers. In an ideal world this routine
4733 * needs to handle all the following classes of redirects...
4734 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4735 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4736 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4737 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004738 *
4739 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4740 * "2.7 Redirection
4741 * ... If n is quoted, the number shall not be recognized as part of
4742 * the redirection expression. For example:
4743 * echo \2>a
4744 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004745 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004746 *
4747 * A -1 return means no valid number was found,
4748 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004749 */
4750static int redirect_opt_num(o_string *o)
4751{
4752 int num;
4753
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004754 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004755 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004756 num = bb_strtou(o->data, NULL, 10);
4757 if (errno || num < 0)
4758 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004759 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004760 return num;
4761}
4762
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004763#if BB_MMU
4764#define fetch_till_str(as_string, input, word, skip_tabs) \
4765 fetch_till_str(input, word, skip_tabs)
4766#endif
4767static char *fetch_till_str(o_string *as_string,
4768 struct in_str *input,
4769 const char *word,
4770 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004771{
4772 o_string heredoc = NULL_O_STRING;
4773 int past_EOL = 0;
4774 int ch;
4775
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004776 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004777 while (1) {
4778 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004779 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004780 if (ch == '\n') {
4781 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4782 heredoc.data[past_EOL] = '\0';
4783 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4784 return heredoc.data;
4785 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004786 do {
4787 o_addchr(&heredoc, ch);
4788 past_EOL = heredoc.length;
4789 jump_in:
4790 do {
4791 ch = i_getch(input);
4792 nommu_addchr(as_string, ch);
4793 } while (skip_tabs && ch == '\t');
4794 } while (ch == '\n');
4795 }
4796 if (ch == EOF) {
4797 o_free_unsafe(&heredoc);
4798 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004799 }
4800 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004801 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004802 }
4803}
4804
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004805/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4806 * and load them all. There should be exactly heredoc_cnt of them.
4807 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004808static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4809{
4810 struct pipe *pi = ctx->list_head;
4811
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004812 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004813 int i;
4814 struct command *cmd = pi->cmds;
4815
4816 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4817 pi->num_cmds,
4818 cmd->argv ? cmd->argv[0] : "NONE");
4819 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004820 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004821
4822 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4823 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004824 while (redir) {
4825 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004826 char *p;
4827
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004828 redir->rd_type = REDIRECT_HEREDOC2;
4829 /* redir->dup is (ab)used to indicate <<- */
4830 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004831 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004832 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004833 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004834 return 1;
4835 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004836 free(redir->rd_filename);
4837 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004838 heredoc_cnt--;
4839 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004840 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004841 }
4842 cmd++;
4843 }
4844 pi = pi->next;
4845 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004846#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004847 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004848 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004849 bb_error_msg_and_die("heredoc BUG 2");
4850#endif
4851 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004852}
4853
4854
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004855#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004856static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004857{
4858 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004859 int pid, channel[2];
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004860#if !BB_MMU
4861 char **to_free;
4862#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004863
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00004864 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00004865 pid = BB_MMU ? fork() : vfork();
4866 if (pid < 0)
4867 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004868
Denis Vlasenko05743d72008-02-10 12:10:08 +00004869 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004870 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004871 /* Process substitution is not considered to be usual
4872 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004873 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4874 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00004875 bb_signals(0
4876 + (1 << SIGTSTP)
4877 + (1 << SIGTTIN)
4878 + (1 << SIGTTOU)
4879 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004880 close(channel[0]); /* NB: close _first_, then move fd! */
4881 xmove_fd(channel[1], 1);
4882 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004883 IF_HUSH_JOB(G.run_list_level = 1;)
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004884#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004885 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004886 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004887 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004888#else
4889 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00004890 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4891 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004892 * echo OK
4893 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004894 re_execute_shell(&to_free,
4895 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004896 G.global_argv[0],
4897 G.global_argv + 1);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004898#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004899 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004900
4901 /* parent */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02004902#if ENABLE_HUSH_FAST
4903 G.count_SIGCHLD++;
4904//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);
4905#endif
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004906 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004907#if !BB_MMU
4908 free(to_free);
4909#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004910 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004911 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00004912 return pf;
4913}
4914
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004915/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004916static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004917{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004918 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004919 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004920 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004921
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004922 pf = generate_stream_from_string(s);
4923 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00004924 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004925 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00004926
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004927 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004928 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004929 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004930 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004931 if (ch == '\n') {
4932 eol_cnt++;
4933 continue;
4934 }
4935 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004936 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004937 eol_cnt--;
4938 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004939 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004940 }
4941
4942 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004943 /* Note: we got EOF, and we just close the read end of the pipe.
4944 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004945 * Try these:
4946 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4947 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004948 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004949 fclose(pf);
4950 debug_printf("closed FILE from child. return 0\n");
4951 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004952}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004953#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004954
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004955static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004956 struct in_str *input, int ch)
4957{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004958 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004959 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004960 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004961 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004962 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004963 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004964
4965 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004966#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004967 if (ch == '(' && !dest->o_quoted) {
4968 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004969 if (done_word(dest, ctx))
4970 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004971 if (!command->argv)
4972 goto skip; /* (... */
4973 if (command->argv[1]) { /* word word ... (... */
4974 syntax_error_unexpected_ch('(');
4975 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004976 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004977 /* it is "word(..." or "word (..." */
4978 do
4979 ch = i_getch(input);
4980 while (ch == ' ' || ch == '\t');
4981 if (ch != ')') {
4982 syntax_error_unexpected_ch(ch);
4983 return 1;
4984 }
4985 nommu_addchr(&ctx->as_string, ch);
4986 do
4987 ch = i_getch(input);
4988 while (ch == ' ' || ch == '\t' || ch == '\n');
4989 if (ch != '{') {
4990 syntax_error_unexpected_ch(ch);
4991 return 1;
4992 }
4993 nommu_addchr(&ctx->as_string, ch);
4994 command->grp_type = GRP_FUNCTION;
4995 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004996 }
4997#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004998 if (command->argv /* word [word]{... */
4999 || dest->length /* word{... */
5000 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005001 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005002 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005003 debug_printf_parse("parse_group return 1: "
5004 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005005 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005006 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005007
5008#if ENABLE_HUSH_FUNCTIONS
5009 skip:
5010#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005011 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005012 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005013 endch = ')';
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005014 command->grp_type = GRP_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00005015 } else {
5016 /* bash does not allow "{echo...", requires whitespace */
5017 ch = i_getch(input);
5018 if (ch != ' ' && ch != '\t' && ch != '\n') {
5019 syntax_error_unexpected_ch(ch);
5020 return 1;
5021 }
5022 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005023 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00005024
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005025 {
5026#if !BB_MMU
5027 char *as_string = NULL;
5028#endif
5029 pipe_list = parse_stream(&as_string, input, endch);
5030#if !BB_MMU
5031 if (as_string)
5032 o_addstr(&ctx->as_string, as_string);
5033#endif
5034 /* empty ()/{} or parse error? */
5035 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00005036 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005037#if !BB_MMU
5038 free(as_string);
5039#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005040 debug_printf_parse("parse_group return 1: "
5041 "parse_stream returned %p\n", pipe_list);
5042 return 1;
5043 }
5044 command->group = pipe_list;
5045#if !BB_MMU
5046 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
5047 command->group_as_string = as_string;
5048 debug_printf_parse("end of group, remembering as:'%s'\n",
5049 command->group_as_string);
5050#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005051 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005052 debug_printf_parse("parse_group return 0\n");
5053 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005054 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00005055}
5056
Mike Frysinger98c52642009-04-02 10:02:37 +00005057#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005058/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005059static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005060/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005061static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005062{
5063 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005064 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005065 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005066 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005067 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005068 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005069 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005070 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005071 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005072 }
5073}
5074/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005075static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005076{
5077 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005078 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005079 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005080 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005081 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005082 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005083 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005084 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005085 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005086 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005087 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005088 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005089 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005090 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005091 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005092 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005093 continue;
5094 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005095 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005096 }
5097}
5098/* Process `cmd` - copy contents until "`" is seen. Complicated by
5099 * \` quoting.
5100 * "Within the backquoted style of command substitution, backslash
5101 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5102 * The search for the matching backquote shall be satisfied by the first
5103 * backquote found without a preceding backslash; during this search,
5104 * if a non-escaped backquote is encountered within a shell comment,
5105 * a here-document, an embedded command substitution of the $(command)
5106 * form, or a quoted string, undefined results occur. A single-quoted
5107 * or double-quoted string that begins, but does not end, within the
5108 * "`...`" sequence produces undefined results."
5109 * Example Output
5110 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5111 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005112static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005113{
5114 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005115 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005116 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005117 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005118 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005119 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005120 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005121 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005122 if (ch == '\\') {
5123 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005124 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005125 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005126 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005127 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005128 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005129 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005130 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005131 ch = ch2;
5132 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005133 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005134 }
5135}
5136/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5137 * quoting and nested ()s.
5138 * "With the $(command) style of command substitution, all characters
5139 * following the open parenthesis to the matching closing parenthesis
5140 * constitute the command. Any valid shell script can be used for command,
5141 * except a script consisting solely of redirections which produces
5142 * unspecified results."
5143 * Example Output
5144 * echo $(echo '(TEST)' BEST) (TEST) BEST
5145 * echo $(echo 'TEST)' BEST) TEST) BEST
5146 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5147 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005148static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005149{
5150 int count = 0;
5151 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005152 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005153 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005154 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005155 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005156 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005157 if (ch == '(')
5158 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005159 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005160 if (--count < 0) {
5161 if (!dbl)
5162 break;
5163 if (i_peek(input) == ')') {
5164 i_getch(input);
5165 break;
5166 }
5167 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005168 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005169 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005170 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005171 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005172 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005173 continue;
5174 }
5175 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005176 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005177 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005178 continue;
5179 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005180 if (ch == '\\') {
5181 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005182 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005183 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005184 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005185 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005186 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005187 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005188 continue;
5189 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005190 }
5191}
Mike Frysinger98c52642009-04-02 10:02:37 +00005192#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005193
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005194/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005195#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005196#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005197 handle_dollar(dest, input)
5198#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005199static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005200 o_string *dest,
5201 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005202{
Mike Frysinger6379bb42009-03-28 18:55:03 +00005203 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005204 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005205 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005206
5207 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005208 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005209 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005210 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005211 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005212 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005213 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005214 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005215 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005216 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005217 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005218 if (!isalnum(ch) && ch != '_')
5219 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005220 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005221 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005222 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005223 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005224 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005225 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005226 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005227 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005228 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005229 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005230 o_addchr(dest, ch | quote_mask);
5231 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005232 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005233 case '$': /* pid */
5234 case '!': /* last bg pid */
5235 case '?': /* last exit code */
5236 case '#': /* number of args */
5237 case '*': /* args */
5238 case '@': /* args */
5239 goto make_one_char_var;
5240 case '{': {
5241 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005242
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005243 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005244 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005245 nommu_addchr(as_string, ch);
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005246 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005247 expansion = 0;
5248 first_char = true;
5249 all_digits = false;
5250 while (1) {
5251 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005252 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005253 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005254 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005255 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005256
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005257 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005258 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005259 /* ${#var}: length of var contents */
5260 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005261 }
5262 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005263 all_digits = true;
5264 goto char_ok;
5265 }
5266 }
5267
5268 if (expansion < 2
5269 && ( (all_digits && !isdigit(ch))
5270 || (!all_digits && !isalnum(ch) && ch != '_')
5271 )
5272 ) {
5273 /* handle parameter expansions
5274 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5275 */
5276 if (first_char)
5277 goto case_default;
5278 switch (ch) {
5279 case ':': /* null modifier */
5280 if (expansion == 0) {
5281 debug_printf_parse(": null modifier\n");
5282 ++expansion;
5283 break;
5284 }
5285 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005286 case '#': /* remove prefix */
5287 case '%': /* remove suffix */
5288 if (expansion == 0) {
5289 debug_printf_parse(": remove suffix/prefix\n");
5290 expansion = 2;
5291 break;
5292 }
5293 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005294 case '-': /* default value */
5295 case '=': /* assign default */
5296 case '+': /* alternative */
5297 case '?': /* error indicate */
5298 debug_printf_parse(": parameter expansion\n");
5299 expansion = 2;
5300 break;
5301 default:
5302 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005303 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005304 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5305 return 1;
5306 }
5307 }
5308 char_ok:
5309 debug_printf_parse(": '%c'\n", ch);
5310 o_addchr(dest, ch | quote_mask);
5311 quote_mask = 0;
5312 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005313 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005314 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5315 break;
5316 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005317#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005318 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005319# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005320 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005321# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005322 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005323 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005324# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005325 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005326 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005327 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005328 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5329 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005330# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005331 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005332# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005333 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005334# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005335 if (as_string) {
5336 o_addstr(as_string, dest->data + pos);
5337 o_addchr(as_string, ')');
5338 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005339 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005340# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005341 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005342 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005343 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005344# endif
5345# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005346 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5347 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005348# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005349 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005350# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005351 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005352# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005353 if (as_string) {
5354 o_addstr(as_string, dest->data + pos);
5355 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005356 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005357# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005358 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005359# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005360 break;
5361 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005362#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005363 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005364 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005365 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005366 ch = i_peek(input);
5367 if (isalnum(ch)) { /* it's $_name or $_123 */
5368 ch = '_';
5369 goto make_var;
5370 }
5371 /* else: it's $_ */
5372 /* TODO: */
5373 /* $_ Shell or shell script name; or last cmd name */
5374 /* $- Option flags set by set builtin or shell options (-i etc) */
5375 default:
5376 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005377 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005378 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005379 return 0;
5380}
5381
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005382#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005383#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005384 parse_stream_dquoted(dest, input, dquote_end)
5385#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005386static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005387 o_string *dest,
5388 struct in_str *input,
5389 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005390{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005391 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005392 int next;
5393
5394 again:
5395 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005396 if (ch != EOF)
5397 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005398 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005399 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005400 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005401 debug_printf_parse("parse_stream_dquoted return 0\n");
5402 return 0;
5403 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005404 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005405 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005406 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005407 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005408 }
5409 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005410 if (ch != '\n') {
5411 next = i_peek(input);
5412 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005413 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5414 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005415 if (ch == '\\') {
5416 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005417 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005418 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005419 }
5420 /* bash:
5421 * "The backslash retains its special meaning [in "..."]
5422 * only when followed by one of the following characters:
5423 * $, `, ", \, or <newline>. A double quote may be quoted
5424 * within double quotes by preceding it with a backslash.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005425 */
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005426 if (strchr("$`\"\\\n", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005427 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005428 if (ch != '\n') {
5429 o_addqchr(dest, ch);
5430 nommu_addchr(as_string, ch);
5431 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005432 } else {
5433 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005434 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005435 }
5436 goto again;
5437 }
5438 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005439 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005440 debug_printf_parse("parse_stream_dquoted return 1: "
5441 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005442 return 1;
5443 }
5444 goto again;
5445 }
5446#if ENABLE_HUSH_TICK
5447 if (ch == '`') {
5448 //int pos = dest->length;
5449 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5450 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005451 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005452 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5453 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005454 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005455 }
5456#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005457 o_addQchr(dest, ch);
5458 if (ch == '='
5459 && (dest->o_assignment == MAYBE_ASSIGNMENT
5460 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005461 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005462 ) {
5463 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5464 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005465 goto again;
5466}
5467
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005468/*
5469 * Scan input until EOF or end_trigger char.
5470 * Return a list of pipes to execute, or NULL on EOF
5471 * or if end_trigger character is met.
5472 * On syntax error, exit is shell is not interactive,
5473 * reset parsing machinery and start parsing anew,
5474 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005475 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005476static struct pipe *parse_stream(char **pstring,
5477 struct in_str *input,
5478 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005479{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005480 struct parse_context ctx;
5481 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005482 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005483 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005484
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005485 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005486 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005487 * found. When recursing, quote state is passed in via dest->o_escape.
5488 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005489 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5490 end_trigger ? : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005491 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005492
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005493 G.ifs = get_local_var_value("IFS");
5494 if (G.ifs == NULL)
5495 G.ifs = " \t\n";
5496
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005497 reset:
5498#if ENABLE_HUSH_INTERACTIVE
5499 input->promptmode = 0; /* PS1 */
5500#endif
5501 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5502 initialize_context(&ctx);
5503 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005504 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005505 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005506 const char *is_ifs;
5507 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005508 int ch;
5509 int next;
5510 int redir_fd;
5511 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005512
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005513 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005514 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005515 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005516 goto parse_error;
5517 }
5518 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005519 is_in_dquote = 0;
5520 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005521 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005522 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5523 ch, ch, dest.o_escape);
5524 if (ch == EOF) {
5525 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005526
5527 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005528 syntax_error_unterm_str("here document");
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005529 goto parse_error;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005530 }
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005531 /* end_trigger == '}' case errors out earlier,
5532 * checking only ')' */
5533 if (end_trigger == ')') {
5534 syntax_error_unterm_ch('('); /* exits */
5535 /* goto parse_error; */
5536 }
5537
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005538 if (done_word(&dest, &ctx)) {
Denys Vlasenkob1cfc452009-05-02 17:18:34 +02005539 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005540 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005541 o_free(&dest);
5542 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005543 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005544 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005545 /* (this makes bare "&" cmd a no-op.
5546 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005547 if (pi->num_cmds == 0
5548 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5549 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005550 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005551 pi = NULL;
5552 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005553#if !BB_MMU
5554 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5555 if (pstring)
5556 *pstring = ctx.as_string.data;
5557 else
5558 o_free_unsafe(&ctx.as_string);
5559#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005560 debug_leave();
5561 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005562 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005563 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005564 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005565 is_ifs = strchr(G.ifs, ch);
5566 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005567 "\\$\"" IF_HUSH_TICK("`") /* always special */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005568 , ch);
5569
5570 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005571 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005572 o_addQchr(&dest, ch);
5573 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5574 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005575 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005576 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005577 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005578 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005579 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005580 continue;
5581 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005582
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005583 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005584 if (done_word(&dest, &ctx)) {
5585 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005586 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005587 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005588#if ENABLE_HUSH_CASE
5589 /* "case ... in <newline> word) ..." -
5590 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005591 if (ctx.command->argv == NULL
5592 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005593 ) {
5594 continue;
5595 }
5596#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005597 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005598 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005599 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5600 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005601 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005602 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005603 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005604 heredoc_cnt = 0;
5605 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005606 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005607 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005608 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005609 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005610 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005611 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005612
5613 /* "cmd}" or "cmd }..." without semicolon or &:
5614 * } is an ordinary char in this case, even inside { cmd; }
5615 * Pathological example: { ""}; } should exec "}" cmd
5616 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005617 if (ch == '}') {
5618 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5619 || dest.length != 0 /* word} */
5620 || dest.o_quoted /* ""} */
5621 ) {
5622 goto ordinary_char;
5623 }
5624 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5625 goto skip_end_trigger;
5626 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005627 }
5628
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005629 if (end_trigger && end_trigger == ch
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005630 && (ch != ';' || heredoc_cnt == 0)
5631#if ENABLE_HUSH_CASE
5632 && (ch != ')'
5633 || ctx.ctx_res_w != RES_MATCH
5634 || (!dest.o_quoted && strcmp(dest.data, "esac") == 0)
5635 )
5636#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005637 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005638 if (heredoc_cnt) {
5639 /* This is technically valid:
5640 * { cat <<HERE; }; echo Ok
5641 * heredoc
5642 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005643 * HERE
5644 * but we don't support this.
5645 * We require heredoc to be in enclosing {}/(),
5646 * if any.
5647 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005648 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005649 goto parse_error;
5650 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005651 if (done_word(&dest, &ctx)) {
5652 goto parse_error;
5653 }
5654 done_pipe(&ctx, PIPE_SEQ);
5655 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005656 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005657 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005658 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005659 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005660 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005661#if !BB_MMU
5662 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5663 if (pstring)
5664 *pstring = ctx.as_string.data;
5665 else
5666 o_free_unsafe(&ctx.as_string);
5667#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005668 debug_leave();
5669 debug_printf_parse("parse_stream return %p: "
5670 "end_trigger char found\n",
5671 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005672 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005673 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005674 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005675 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005676 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005677 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005678
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005679 next = '\0';
5680 if (ch != '\n') {
5681 next = i_peek(input);
5682 }
5683
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005684 /* Catch <, > before deciding whether this word is
5685 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5686 switch (ch) {
5687 case '>':
5688 redir_fd = redirect_opt_num(&dest);
5689 if (done_word(&dest, &ctx)) {
5690 goto parse_error;
5691 }
5692 redir_style = REDIRECT_OVERWRITE;
5693 if (next == '>') {
5694 redir_style = REDIRECT_APPEND;
5695 ch = i_getch(input);
5696 nommu_addchr(&ctx.as_string, ch);
5697 }
5698#if 0
5699 else if (next == '(') {
5700 syntax_error(">(process) not supported");
5701 goto parse_error;
5702 }
5703#endif
5704 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5705 goto parse_error;
5706 continue; /* back to top of while (1) */
5707 case '<':
5708 redir_fd = redirect_opt_num(&dest);
5709 if (done_word(&dest, &ctx)) {
5710 goto parse_error;
5711 }
5712 redir_style = REDIRECT_INPUT;
5713 if (next == '<') {
5714 redir_style = REDIRECT_HEREDOC;
5715 heredoc_cnt++;
5716 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5717 ch = i_getch(input);
5718 nommu_addchr(&ctx.as_string, ch);
5719 } else if (next == '>') {
5720 redir_style = REDIRECT_IO;
5721 ch = i_getch(input);
5722 nommu_addchr(&ctx.as_string, ch);
5723 }
5724#if 0
5725 else if (next == '(') {
5726 syntax_error("<(process) not supported");
5727 goto parse_error;
5728 }
5729#endif
5730 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5731 goto parse_error;
5732 continue; /* back to top of while (1) */
5733 }
5734
5735 if (dest.o_assignment == MAYBE_ASSIGNMENT
5736 /* check that we are not in word in "a=1 2>word b=1": */
5737 && !ctx.pending_redirect
5738 ) {
5739 /* ch is a special char and thus this word
5740 * cannot be an assignment */
5741 dest.o_assignment = NOT_ASSIGNMENT;
5742 }
5743
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005744 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00005745 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005746 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005747 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005748 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005749 if (ch == EOF || ch == '\n')
5750 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005751 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005752 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005753 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005754 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00005755 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005756 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005757 }
5758 break;
5759 case '\\':
5760 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005761 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005762 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005763 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005764 ch = i_getch(input);
Denys Vlasenkoe19e1932009-05-03 02:15:18 +02005765 if (ch != '\n') {
5766 o_addchr(&dest, '\\');
5767 nommu_addchr(&ctx.as_string, '\\');
5768 o_addchr(&dest, ch);
5769 nommu_addchr(&ctx.as_string, ch);
5770 /* Example: echo Hello \2>file
5771 * we need to know that word 2 is quoted */
5772 dest.o_quoted = 1;
5773 }
Eric Andersen25f27032001-04-26 23:22:31 +00005774 break;
5775 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005776 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005777 debug_printf_parse("parse_stream parse error: "
5778 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005779 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005780 }
Eric Andersen25f27032001-04-26 23:22:31 +00005781 break;
5782 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005783 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005784 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005785 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005786 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005787 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005788 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005789 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005790 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005791 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005792 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005793 if (dest.o_assignment == NOT_ASSIGNMENT)
5794 o_addqchr(&dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005795 else
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005796 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005797 }
Eric Andersen25f27032001-04-26 23:22:31 +00005798 break;
5799 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005800 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005801 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005802 if (dest.o_assignment == NOT_ASSIGNMENT)
5803 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005804 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005805#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005806 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005807#if !BB_MMU
5808 int pos;
5809#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005810 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5811 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005812#if !BB_MMU
5813 pos = dest.length;
5814#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005815 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005816#if !BB_MMU
5817 o_addstr(&ctx.as_string, dest.data + pos);
5818 o_addchr(&ctx.as_string, '`');
5819#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005820 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5821 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005822 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005823 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005824#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005825 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005826#if ENABLE_HUSH_CASE
5827 case_semi:
5828#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005829 if (done_word(&dest, &ctx)) {
5830 goto parse_error;
5831 }
5832 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005833#if ENABLE_HUSH_CASE
5834 /* Eat multiple semicolons, detect
5835 * whether it means something special */
5836 while (1) {
5837 ch = i_peek(input);
5838 if (ch != ';')
5839 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005840 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005841 nommu_addchr(&ctx.as_string, ch);
Denys Vlasenkoe9bda902009-05-23 16:50:07 +02005842 if (ctx.ctx_res_w == RES_CASE_BODY) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005843 ctx.ctx_dsemicolon = 1;
5844 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005845 break;
5846 }
5847 }
5848#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005849 new_cmd:
5850 /* We just finished a cmd. New one may start
5851 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005852 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00005853 break;
5854 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005855 if (done_word(&dest, &ctx)) {
5856 goto parse_error;
5857 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005858 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005859 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005860 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005861 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005862 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005863 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005864 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005865 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005866 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005867 if (done_word(&dest, &ctx)) {
5868 goto parse_error;
5869 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005870#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005871 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005872 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005873#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005874 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005875 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005876 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005877 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005878 } else {
5879 /* we could pick up a file descriptor choice here
5880 * with redirect_opt_num(), but bash doesn't do it.
5881 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005882 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005883 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005884 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005885 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005886#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005887 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005888 if (ctx.ctx_res_w == RES_MATCH
5889 && ctx.command->argv == NULL /* not (word|(... */
5890 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005891 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005892 ) {
5893 continue;
5894 }
5895#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005896 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005897 if (parse_group(&dest, &ctx, input, ch) != 0) {
5898 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005899 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005900 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005901 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005902#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005903 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005904 goto case_semi;
5905#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005906 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005907 /* proper use of this character is caught by end_trigger:
5908 * if we see {, we call parse_group(..., end_trigger='}')
5909 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005910 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005911 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005912 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005913 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005914 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005915 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005916 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005917
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005918 parse_error:
5919 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005920 struct parse_context *pctx;
5921 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005922
5923 /* Clean up allocated tree.
5924 * Samples for finding leaks on syntax error recovery path.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005925 * Run them from interactive shell, watch pmap `pidof hush`.
5926 * while if false; then false; fi do break; done
5927 * (bash accepts it)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005928 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005929 * Samples to catch leaks at execution:
5930 * while if (true | {true;}); then echo ok; fi; do break; done
5931 * 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 +00005932 */
5933 pctx = &ctx;
5934 do {
5935 /* Update pipe/command counts,
5936 * otherwise freeing may miss some */
5937 done_pipe(pctx, PIPE_SEQ);
5938 debug_printf_clean("freeing list %p from ctx %p\n",
5939 pctx->list_head, pctx);
5940 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005941 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005942 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005943#if !BB_MMU
5944 o_free_unsafe(&pctx->as_string);
5945#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005946 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005947 if (pctx != &ctx) {
5948 free(pctx);
5949 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005950 IF_HAS_KEYWORDS(pctx = p2;)
5951 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005952 /* Free text, clear all dest fields */
5953 o_free(&dest);
5954 /* If we are not in top-level parse, we return,
5955 * our caller will propagate error.
5956 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005957 if (end_trigger != ';') {
5958#if !BB_MMU
5959 if (pstring)
5960 *pstring = NULL;
5961#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005962 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005963 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005964 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005965 /* Discard cached input, force prompt */
5966 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005967 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005968 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005969 }
Eric Andersen25f27032001-04-26 23:22:31 +00005970}
5971
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005972/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005973 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5974 * end_trigger controls how often we stop parsing
5975 * NUL: parse all, execute, return
5976 * ';': parse till ';' or newline, execute, repeat till EOF
5977 */
5978static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005979{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005980 while (1) {
5981 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005982
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005983 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005984 if (!pipe_list) /* EOF */
5985 break;
5986 debug_print_tree(pipe_list, 0);
5987 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5988 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005989 }
Eric Andersen25f27032001-04-26 23:22:31 +00005990}
5991
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005992static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005993{
5994 struct in_str input;
5995 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005996 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005997}
5998
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005999static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00006000{
Eric Andersen25f27032001-04-26 23:22:31 +00006001 struct in_str input;
6002 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006003 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00006004}
6005
Denis Vlasenkof9375282009-04-05 19:13:39 +00006006/* Called a few times only (or even once if "sh -c") */
6007static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00006008{
Denis Vlasenkof9375282009-04-05 19:13:39 +00006009 unsigned sig;
6010 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006011
Denis Vlasenkof9375282009-04-05 19:13:39 +00006012 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006013 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00006014 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Mike Frysinger38478a62009-05-20 04:48:06 -04006015 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006016 mask |= SPECIAL_JOB_SIGS;
6017 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006018 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00006019
Denis Vlasenkof9375282009-04-05 19:13:39 +00006020 if (!second_time)
6021 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
6022 sig = 0;
6023 while (mask) {
6024 if (mask & 1)
6025 sigaddset(&G.blocked_set, sig);
6026 mask >>= 1;
6027 sig++;
6028 }
6029 sigdelset(&G.blocked_set, SIGCHLD);
6030
6031 sigprocmask(SIG_SETMASK, &G.blocked_set,
6032 second_time ? NULL : &G.inherited_set);
6033 /* POSIX allows shell to re-enable SIGCHLD
6034 * even if it was SIG_IGN on entry */
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006035#if ENABLE_HUSH_FAST
6036 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006037 if (!second_time)
Denys Vlasenko8d7be232009-05-25 16:38:32 +02006038 signal(SIGCHLD, SIGCHLD_handler);
6039#else
6040 if (!second_time)
6041 signal(SIGCHLD, SIG_DFL);
6042#endif
Denis Vlasenkof9375282009-04-05 19:13:39 +00006043}
6044
6045#if ENABLE_HUSH_JOB
6046/* helper */
6047static void maybe_set_to_sigexit(int sig)
6048{
6049 void (*handler)(int);
6050 /* non_DFL_mask'ed signals are, well, masked,
6051 * no need to set handler for them.
6052 */
6053 if (!((G.non_DFL_mask >> sig) & 1)) {
6054 handler = signal(sig, sigexit);
6055 if (handler == SIG_IGN) /* oops... restore back to IGN! */
6056 signal(sig, handler);
6057 }
6058}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006059/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006060static void set_fatal_handlers(void)
6061{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00006062 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006063 if (HUSH_DEBUG) {
6064 maybe_set_to_sigexit(SIGILL );
6065 maybe_set_to_sigexit(SIGFPE );
6066 maybe_set_to_sigexit(SIGBUS );
6067 maybe_set_to_sigexit(SIGSEGV);
6068 maybe_set_to_sigexit(SIGTRAP);
6069 } /* else: hush is perfect. what SEGV? */
6070 maybe_set_to_sigexit(SIGABRT);
6071 /* bash 3.2 seems to handle these just like 'fatal' ones */
6072 maybe_set_to_sigexit(SIGPIPE);
6073 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006074 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00006075 * if we aren't interactive... but in this case
6076 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006077 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00006078 /*maybe_set_to_sigexit(SIGTERM);*/
6079 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00006080}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00006081#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00006082
Denis Vlasenkod5762932009-03-31 11:22:57 +00006083static int set_mode(const char cstate, const char mode)
6084{
6085 int state = (cstate == '-' ? 1 : 0);
6086 switch (mode) {
6087 case 'n': G.fake_mode = state; break;
6088 case 'x': /*G.debug_mode = state;*/ break;
6089 default: return EXIT_FAILURE;
6090 }
6091 return EXIT_SUCCESS;
6092}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006093
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00006094int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00006095int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00006096{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006097 static const struct variable const_shell_ver = {
6098 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006099 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006100 .max_len = 1, /* 0 can provoke free(name) */
6101 .flg_export = 1,
6102 .flg_read_only = 1,
6103 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006104 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006105 int opt;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006106 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006107 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006108
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006109 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006110 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006111 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006112#if !BB_MMU
6113 G.argv0_for_re_execing = argv[0];
6114#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006115 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006116 G.shell_ver = const_shell_ver; /* copying struct here */
6117 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006118 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006119 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6120 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006121 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006122 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006123 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006124 if (e) while (*e) {
6125 char *value = strchr(*e, '=');
6126 if (value) { /* paranoia */
6127 cur_var->next = xzalloc(sizeof(*cur_var));
6128 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006129 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006130 cur_var->max_len = strlen(*e);
6131 cur_var->flg_export = 1;
6132 }
6133 e++;
6134 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006135 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006136 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenko38f63192007-01-22 09:03:07 +00006137#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006138 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006139#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006140 G.global_argc = argc;
6141 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006142 /* Initialize some more globals to non-zero values */
6143 set_cwd();
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006144 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006145
Denis Vlasenkoed782372009-04-10 00:45:02 +00006146 if (setjmp(die_jmp)) {
6147 /* xfunc has failed! die die die */
6148 /* no EXIT traps, this is an escape hatch! */
6149 G.exiting = 1;
6150 hush_exit(xfunc_error_retval);
6151 }
6152
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006153 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006154 * block_signals(0) if we are going to execute "sh <script>",
6155 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006156 * If we later decide that we are interactive, we run block_signals(0)
6157 * (or re-run block_signals(1) if we ran block_signals(0) before)
6158 * in order to intercept (more) signals.
6159 */
6160
6161 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006162 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006163 while (1) {
6164 opt = getopt(argc, argv, "c:xins"
6165#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006166 "<:$:R:V:"
6167# if ENABLE_HUSH_FUNCTIONS
6168 "F:"
6169# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006170#endif
6171 );
6172 if (opt <= 0)
6173 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006174 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006175 case 'c':
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006176 if (!G.root_pid)
6177 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00006178 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00006179 if (!argv[optind]) {
6180 /* -c 'script' (no params): prevent empty $0 */
6181 *--G.global_argv = argv[0];
6182 optind--;
6183 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006184 G.global_argc = argc - optind;
Denis Vlasenkof9375282009-04-05 19:13:39 +00006185 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006186 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006187 goto final_return;
6188 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006189 /* Well, we cannot just declare interactiveness,
6190 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006191 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006192 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006193 case 's':
6194 /* "-s" means "read from stdin", but this is how we always
6195 * operate, so simply do nothing here. */
6196 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006197#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006198 case '<': /* "big heredoc" support */
6199 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6200 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006201 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006202 G.root_pid = bb_strtou(optarg, &optarg, 16);
6203 optarg++;
6204 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6205 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006206 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006207# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006208 optarg++;
6209 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006210# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006211 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006212 case 'R':
6213 case 'V':
6214 set_local_var(xstrdup(optarg), 0, opt == 'R');
6215 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006216# if ENABLE_HUSH_FUNCTIONS
6217 case 'F': {
6218 struct function *funcp = new_function(optarg);
6219 /* funcp->name is already set to optarg */
6220 /* funcp->body is set to NULL. It's a special case. */
6221 funcp->body_as_string = argv[optind];
6222 optind++;
6223 break;
6224 }
6225# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006226#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006227 case 'n':
6228 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006229 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006230 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006231 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006232#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006233 fprintf(stderr, "Usage: sh [FILE]...\n"
6234 " or: sh -c command [args]...\n\n");
6235 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006236#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006237 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006238#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006239 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006240 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006241
6242 if (!G.root_pid)
6243 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00006244
6245 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006246 if (argv[0] && argv[0][0] == '-') {
6247 FILE *input;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006248 debug_printf("sourcing /etc/profile\n");
6249 input = fopen_for_read("/etc/profile");
6250 if (input != NULL) {
6251 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006252 block_signals(0); /* 0: called 1st time */
6253 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006254 parse_and_run_file(input);
6255 fclose(input);
6256 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006257 /* bash: after sourcing /etc/profile,
6258 * tries to source (in the given order):
6259 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6260 * stopping of first found. --noprofile turns this off.
6261 * bash also sources ~/.bash_logout on exit.
6262 * If called as sh, skips .bash_XXX files.
6263 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006264 }
6265
Denis Vlasenkof9375282009-04-05 19:13:39 +00006266 if (argv[optind]) {
6267 FILE *input;
6268 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006269 * "bash <script>" (which is never interactive (unless -i?))
6270 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006271 * If called as sh, does the same but with $ENV.
6272 */
6273 debug_printf("running script '%s'\n", argv[optind]);
6274 G.global_argv = argv + optind;
6275 G.global_argc = argc - optind;
6276 input = xfopen_for_read(argv[optind]);
6277 close_on_exec_on(fileno(input));
6278 if (!signal_mask_is_inited)
6279 block_signals(0); /* 0: called 1st time */
6280 parse_and_run_file(input);
6281#if ENABLE_FEATURE_CLEAN_UP
6282 fclose(input);
6283#endif
6284 goto final_return;
6285 }
6286
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006287 /* Up to here, shell was non-interactive. Now it may become one.
6288 * NB: don't forget to (re)run block_signals(0/1) as needed.
6289 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006290
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006291 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00006292 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006293 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006294 * no arguments remaining or the -s flag given
6295 * standard input is a terminal
6296 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006297 * Refer to Posix.2, the description of the 'sh' utility.
6298 */
6299#if ENABLE_HUSH_JOB
6300 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Mike Frysinger38478a62009-05-20 04:48:06 -04006301 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
6302 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
6303 if (G_saved_tty_pgrp < 0)
6304 G_saved_tty_pgrp = 0;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006305
6306 /* try to dup stdin to high fd#, >= 255 */
6307 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6308 if (G_interactive_fd < 0) {
6309 /* try to dup to any fd */
6310 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006311 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006312 /* give up */
6313 G_interactive_fd = 0;
Mike Frysinger38478a62009-05-20 04:48:06 -04006314 G_saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006315 }
6316 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006317// TODO: track & disallow any attempts of user
6318// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006319 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006320 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006321 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006322 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006323
Mike Frysinger38478a62009-05-20 04:48:06 -04006324 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006325 /* If we were run as 'hush &', sleep until we are
6326 * in the foreground (tty pgrp == our pgrp).
6327 * If we get started under a job aware app (like bash),
6328 * make sure we are now in charge so we don't fight over
6329 * who gets the foreground */
6330 while (1) {
6331 pid_t shell_pgrp = getpgrp();
Mike Frysinger38478a62009-05-20 04:48:06 -04006332 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6333 if (G_saved_tty_pgrp == shell_pgrp)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006334 break;
6335 /* send TTIN to ourself (should stop us) */
6336 kill(- shell_pgrp, SIGTTIN);
6337 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006338 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006339
Denis Vlasenkof9375282009-04-05 19:13:39 +00006340 /* Block some signals */
6341 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006342
Mike Frysinger38478a62009-05-20 04:48:06 -04006343 if (G_saved_tty_pgrp) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006344 /* Set other signals to restore saved_tty_pgrp */
6345 set_fatal_handlers();
6346 /* Put ourselves in our own process group
6347 * (bash, too, does this only if ctty is available) */
6348 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6349 /* Grab control of the terminal */
6350 tcsetpgrp(G_interactive_fd, getpid());
6351 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006352 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006353 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006354 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006355 } else if (!signal_mask_is_inited) {
6356 block_signals(0); /* 0: called 1st time */
6357 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006358#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006359 /* No job control compiled in, only prompt/line editing */
6360 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006361 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6362 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006363 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006364 G_interactive_fd = dup(STDIN_FILENO);
6365 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006366 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006367 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006368 }
6369 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006370 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006371 close_on_exec_on(G_interactive_fd);
6372 block_signals(signal_mask_is_inited);
6373 } else if (!signal_mask_is_inited) {
6374 block_signals(0);
6375 }
6376#else
6377 /* We have interactiveness code disabled */
6378 if (!signal_mask_is_inited) {
6379 block_signals(0);
6380 }
6381#endif
6382 /* bash:
6383 * if interactive but not a login shell, sources ~/.bashrc
6384 * (--norc turns this off, --rcfile <file> overrides)
6385 */
6386
6387 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006388 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysinger26cf2832009-04-24 06:40:30 +00006389 if (ENABLE_HUSH_HELP)
6390 puts("Enter 'help' for a list of built-in commands.");
6391 puts("");
Mike Frysingerb2705e12009-03-23 08:44:02 +00006392 }
6393
Denis Vlasenkof9375282009-04-05 19:13:39 +00006394 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006395
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006396 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006397#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006398 if (G.cwd != bb_msg_unknown)
6399 free((char*)G.cwd);
6400 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006401 while (cur_var) {
6402 struct variable *tmp = cur_var;
6403 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006404 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006405 cur_var = cur_var->next;
6406 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006407 }
Eric Andersen25f27032001-04-26 23:22:31 +00006408#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006409 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006410}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006411
6412
6413#if ENABLE_LASH
6414int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6415int lash_main(int argc, char **argv)
6416{
6417 //bb_error_msg("lash is deprecated, please use hush instead");
6418 return hush_main(argc, argv);
6419}
6420#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006421
6422
6423/*
6424 * Built-ins
6425 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006426static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006427{
6428 return 0;
6429}
6430
6431static int builtin_test(char **argv)
6432{
6433 int argc = 0;
6434 while (*argv) {
6435 argc++;
6436 argv++;
6437 }
6438 return test_main(argc, argv - argc);
6439}
6440
6441static int builtin_echo(char **argv)
6442{
6443 int argc = 0;
6444 while (*argv) {
6445 argc++;
6446 argv++;
6447 }
6448 return echo_main(argc, argv - argc);
6449}
6450
6451static int builtin_eval(char **argv)
6452{
6453 int rcode = EXIT_SUCCESS;
6454
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006455 if (*++argv) {
6456 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006457 /* bash:
6458 * eval "echo Hi; done" ("done" is syntax error):
6459 * "echo Hi" will not execute too.
6460 */
6461 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006462 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006463 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006464 }
6465 return rcode;
6466}
6467
6468static int builtin_cd(char **argv)
6469{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006470 const char *newdir = argv[1];
6471 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006472 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006473 * bash says "bash: cd: HOME not set" and does nothing
6474 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006475 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006476 newdir = get_local_var_value("HOME") ? : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006477 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006478 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006479 /* Mimic bash message exactly */
6480 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006481 return EXIT_FAILURE;
6482 }
6483 set_cwd();
6484 return EXIT_SUCCESS;
6485}
6486
6487static int builtin_exec(char **argv)
6488{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006489 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006490 return EXIT_SUCCESS; /* bash does this */
6491 {
6492#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006493 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006494#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006495 /* TODO: if exec fails, bash does NOT exit! We do... */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006496 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006497 /* never returns */
6498 }
6499}
6500
6501static int builtin_exit(char **argv)
6502{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006503 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00006504
6505 /* interactive bash:
6506 * # trap "echo EEE" EXIT
6507 * # exit
6508 * exit
6509 * There are stopped jobs.
6510 * (if there are _stopped_ jobs, running ones don't count)
6511 * # exit
6512 * exit
6513 # EEE (then bash exits)
6514 *
6515 * we can use G.exiting = -1 as indicator "last cmd was exit"
6516 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006517
6518 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006519 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006520 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006521 /* mimic bash: exit 123abc == exit 255 + error msg */
6522 xfunc_error_retval = 255;
6523 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006524 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006525}
6526
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006527static void print_escaped(const char *s)
6528{
6529 do {
6530 if (*s != '\'') {
6531 const char *p;
6532
6533 p = strchrnul(s, '\'');
6534 /* print 'xxxx', possibly just '' */
6535 printf("'%.*s'", (int)(p - s), s);
6536 if (*p == '\0')
6537 break;
6538 s = p;
6539 }
6540 /* s points to '; print "'''...'''" */
6541 putchar('"');
6542 do putchar('\''); while (*++s == '\'');
6543 putchar('"');
6544 } while (*s);
6545}
6546
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006547static int builtin_export(char **argv)
6548{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006549 unsigned opt_unexport;
6550
6551 if (argv[1] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006552 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006553 if (e) {
6554 while (*e) {
6555#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006556 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006557#else
6558 /* ash emits: export VAR='VAL'
6559 * bash: declare -x VAR="VAL"
6560 * we follow ash example */
6561 const char *s = *e++;
6562 const char *p = strchr(s, '=');
6563
6564 if (!p) /* wtf? take next variable */
6565 continue;
6566 /* export var= */
6567 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006568 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006569 putchar('\n');
6570#endif
6571 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006572 /*fflush(stdout); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006573 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006574 return EXIT_SUCCESS;
6575 }
6576
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006577#if ENABLE_HUSH_EXPORT_N
Denis Vlasenko28e67962009-04-26 23:22:40 +00006578 /* "!": do not abort on errors */
6579 /* "+": stop at 1st non-option */
6580 opt_unexport = getopt32(argv, "!+n");
6581 if (opt_unexport == (unsigned)-1)
6582 return EXIT_FAILURE;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006583 argv += optind;
6584#else
6585 opt_unexport = 0;
6586 argv++;
6587#endif
6588
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006589 do {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006590 char *name = *argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006591
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006592 /* So far we do not check that name is valid (TODO?) */
6593
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006594 if (strchr(name, '=') == NULL) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006595 struct variable *var;
6596
6597 var = get_local_var(name);
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006598 if (opt_unexport) {
6599 /* export -n NAME (without =VALUE) */
6600 if (var) {
6601 var->flg_export = 0;
6602 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6603 unsetenv(name);
6604 } /* else: export -n NOT_EXISTING_VAR: no-op */
6605 continue;
6606 }
6607 /* export NAME (without =VALUE) */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006608 if (var) {
6609 var->flg_export = 1;
6610 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6611 putenv(var->varstr);
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006612 continue;
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006613 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006614 /* Exporting non-existing variable.
6615 * bash does not put it in environment,
6616 * but remembers that it is exported,
6617 * and does put it in env when it is set later.
6618 * We just set it to "" and export. */
6619 name = xasprintf("%s=", name);
6620 } else {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006621 /* (Un)exporting NAME=VALUE */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006622 name = xstrdup(name);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006623 }
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006624 set_local_var(name,
6625 /*export:*/ (opt_unexport ? -1 : 1),
6626 /*readonly:*/ 0
6627 );
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006628 } while (*++argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006629
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006630 return EXIT_SUCCESS;
6631}
6632
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006633static int builtin_trap(char **argv)
6634{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006635 int sig;
6636 char *new_cmd;
6637
6638 if (!G.traps)
6639 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6640
6641 argv++;
6642 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00006643 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006644 /* No args: print all trapped */
6645 for (i = 0; i < NSIG; ++i) {
6646 if (G.traps[i]) {
6647 printf("trap -- ");
6648 print_escaped(G.traps[i]);
6649 printf(" %s\n", get_signame(i));
6650 }
6651 }
6652 /*fflush(stdout); - done after each builtin anyway */
6653 return EXIT_SUCCESS;
6654 }
6655
6656 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006657 /* If first arg is a number: reset all specified signals */
6658 sig = bb_strtou(*argv, NULL, 10);
6659 if (errno == 0) {
6660 int ret;
6661 process_sig_list:
6662 ret = EXIT_SUCCESS;
6663 while (*argv) {
6664 sig = get_signum(*argv++);
6665 if (sig < 0 || sig >= NSIG) {
6666 ret = EXIT_FAILURE;
6667 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00006668 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006669 continue;
6670 }
6671
6672 free(G.traps[sig]);
6673 G.traps[sig] = xstrdup(new_cmd);
6674
6675 debug_printf("trap: setting SIG%s (%i) to '%s'",
6676 get_signame(sig), sig, G.traps[sig]);
6677
6678 /* There is no signal for 0 (EXIT) */
6679 if (sig == 0)
6680 continue;
6681
6682 if (new_cmd) {
6683 sigaddset(&G.blocked_set, sig);
6684 } else {
6685 /* There was a trap handler, we are removing it
6686 * (if sig has non-DFL handling,
6687 * we don't need to do anything) */
6688 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6689 continue;
6690 sigdelset(&G.blocked_set, sig);
6691 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006692 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00006693 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006694 return ret;
6695 }
6696
6697 if (!argv[1]) { /* no second arg */
6698 bb_error_msg("trap: invalid arguments");
6699 return EXIT_FAILURE;
6700 }
6701
6702 /* First arg is "-": reset all specified to default */
6703 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6704 /* Everything else: set arg as signal handler
6705 * (includes "" case, which ignores signal) */
6706 if (argv[0][0] == '-') {
6707 if (argv[0][1] == '\0') { /* "-" */
6708 /* new_cmd remains NULL: "reset these sigs" */
6709 goto reset_traps;
6710 }
6711 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6712 argv++;
6713 }
6714 /* else: "-something", no special meaning */
6715 }
6716 new_cmd = *argv;
6717 reset_traps:
6718 argv++;
6719 goto process_sig_list;
6720}
6721
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006722#if ENABLE_HUSH_JOB
6723/* built-in 'fg' and 'bg' handler */
6724static int builtin_fg_bg(char **argv)
6725{
6726 int i, jobnum;
6727 struct pipe *pi;
6728
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006729 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006730 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006731
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006732 /* If they gave us no args, assume they want the last backgrounded task */
6733 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006734 for (pi = G.job_list; pi; pi = pi->next) {
6735 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006736 goto found;
6737 }
6738 }
6739 bb_error_msg("%s: no current job", argv[0]);
6740 return EXIT_FAILURE;
6741 }
6742 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6743 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6744 return EXIT_FAILURE;
6745 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006746 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006747 if (pi->jobid == jobnum) {
6748 goto found;
6749 }
6750 }
6751 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6752 return EXIT_FAILURE;
6753 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006754 /* TODO: bash prints a string representation
6755 * of job being foregrounded (like "sleep 1 | cat") */
Mike Frysinger38478a62009-05-20 04:48:06 -04006756 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006757 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006758 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006759 }
6760
6761 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006762 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6763 for (i = 0; i < pi->num_cmds; i++) {
6764 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6765 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006766 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006767 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006768
6769 i = kill(- pi->pgrp, SIGCONT);
6770 if (i < 0) {
6771 if (errno == ESRCH) {
6772 delete_finished_bg_job(pi);
6773 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006774 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006775 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006776 }
6777
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006778 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006779 remove_bg_job(pi);
6780 return checkjobs_and_fg_shell(pi);
6781 }
6782 return EXIT_SUCCESS;
6783}
6784#endif
6785
6786#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006787static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006788{
6789 const struct built_in_command *x;
6790
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006791 printf("\n"
6792 "Built-in commands:\n"
6793 "------------------\n");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006794 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6795 printf("%s\t%s\n", x->cmd, x->descr);
6796 }
6797 printf("\n\n");
6798 return EXIT_SUCCESS;
6799}
6800#endif
6801
6802#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006803static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006804{
6805 struct pipe *job;
6806 const char *status_string;
6807
Denis Vlasenko87a86552008-07-29 19:43:10 +00006808 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006809 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006810 status_string = "Stopped";
6811 else
6812 status_string = "Running";
6813
6814 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6815 }
6816 return EXIT_SUCCESS;
6817}
6818#endif
6819
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00006820#if HUSH_DEBUG
6821static int builtin_memleak(char **argv UNUSED_PARAM)
6822{
6823 void *p;
6824 unsigned long l;
6825
6826 /* Crude attempt to find where "free memory" starts,
6827 * sans fragmentation. */
6828 p = malloc(240);
6829 l = (unsigned long)p;
6830 free(p);
6831 p = malloc(3400);
6832 if (l < (unsigned long)p) l = (unsigned long)p;
6833 free(p);
6834
6835 if (!G.memleak_value)
6836 G.memleak_value = l;
6837
6838 l -= G.memleak_value;
6839 if ((long)l < 0)
6840 l = 0;
6841 l /= 1024;
6842 if (l > 127)
6843 l = 127;
6844
6845 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6846 return l;
6847}
6848#endif
6849
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006850static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006851{
6852 puts(set_cwd());
6853 return EXIT_SUCCESS;
6854}
6855
6856static int builtin_read(char **argv)
6857{
6858 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006859 const char *name = "REPLY";
6860
6861 if (argv[1]) {
6862 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006863 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6864 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006865 if (!is_well_formed_var_name(name, '\0')) {
6866 /* Mimic bash message */
6867 bb_error_msg("read: '%s': not a valid identifier", name);
6868 return 1;
6869 }
6870 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006871
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006872//TODO: bash unbackslashes input, splits words and puts them in argv[i]
6873
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006874 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006875 return set_local_var(string, 0, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006876}
6877
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006878/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6879 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006880 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006881 * set [-abCefhmnuvx] [-o option] [argument...]
6882 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006883 * set -- [argument...]
6884 * set -o
6885 * set +o
6886 * Implementations shall support the options in both their hyphen and
6887 * plus-sign forms. These options can also be specified as options to sh.
6888 * Examples:
6889 * Write out all variables and their values: set
6890 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6891 * Turn on the -x and -v options: set -xv
6892 * Unset all positional parameters: set --
6893 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6894 * Set the positional parameters to the expansion of x, even if x expands
6895 * with a leading '-' or '+': set -- $x
6896 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006897 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006898 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006899static int builtin_set(char **argv)
6900{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006901 int n;
6902 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006903 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006904
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006905 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006906 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00006907 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006908 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006909 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006910 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006911
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006912 do {
6913 if (!strcmp(arg, "--")) {
6914 ++argv;
6915 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006916 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00006917 if (arg[0] != '+' && arg[0] != '-')
6918 break;
6919 for (n = 1; arg[n]; ++n)
6920 if (set_mode(arg[0], arg[n]))
6921 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006922 } while ((arg = *++argv) != NULL);
6923 /* Now argv[0] is 1st argument */
6924
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006925 if (arg == NULL)
6926 return EXIT_SUCCESS;
6927 set_argv:
6928
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006929 /* NB: G.global_argv[0] ($0) is never freed/changed */
6930 g_argv = G.global_argv;
6931 if (G.global_args_malloced) {
6932 pp = g_argv;
6933 while (*++pp)
6934 free(*pp);
6935 g_argv[1] = NULL;
6936 } else {
6937 G.global_args_malloced = 1;
6938 pp = xzalloc(sizeof(pp[0]) * 2);
6939 pp[0] = g_argv[0]; /* retain $0 */
6940 g_argv = pp;
6941 }
6942 /* This realloc's G.global_argv */
6943 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6944
6945 n = 1;
6946 while (*++pp)
6947 n++;
6948 G.global_argc = n;
6949
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006950 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006951
6952 /* Nothing known, so abort */
6953 error:
6954 bb_error_msg("set: %s: invalid option", arg);
6955 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006956}
6957
6958static int builtin_shift(char **argv)
6959{
6960 int n = 1;
6961 if (argv[1]) {
6962 n = atoi(argv[1]);
6963 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006964 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006965 if (G.global_args_malloced) {
6966 int m = 1;
6967 while (m <= n)
6968 free(G.global_argv[m++]);
6969 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006970 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006971 memmove(&G.global_argv[1], &G.global_argv[n+1],
6972 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006973 return EXIT_SUCCESS;
6974 }
6975 return EXIT_FAILURE;
6976}
6977
6978static int builtin_source(char **argv)
6979{
Denys Vlasenko54e08432009-05-02 02:34:19 +02006980 const char *PATH;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006981 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00006982 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00006983#if ENABLE_HUSH_FUNCTIONS
6984 smallint sv_flg;
6985#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006986
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006987 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006988 return EXIT_FAILURE;
6989
Denys Vlasenko54e08432009-05-02 02:34:19 +02006990 if (strchr(*argv, '/') == NULL
6991 && (PATH = get_local_var_value("PATH")) != NULL
6992 ) {
6993 /* Search through $PATH */
6994 while (1) {
6995 const char *end = strchrnul(PATH, ':');
6996 int sz = end - PATH; /* must be int! */
6997
6998 if (sz != 0) {
6999 char *tmp = xasprintf("%.*s/%s", sz, PATH, *argv);
7000 input = fopen_for_read(tmp);
7001 free(tmp);
7002 } else {
7003 /* We have xxx::yyyy in $PATH,
7004 * it means "use current dir" */
7005 input = fopen_for_read(*argv);
7006 }
7007 if (input)
7008 goto opened_ok;
7009 if (*end == '\0')
7010 break;
7011 PATH = end + 1;
7012 }
7013 }
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007014 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007015 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007016 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007017 return EXIT_FAILURE;
7018 }
Denys Vlasenko54e08432009-05-02 02:34:19 +02007019 opened_ok:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007020 close_on_exec_on(fileno(input));
7021
Mike Frysinger885b6f22009-04-18 21:04:25 +00007022#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007023 sv_flg = G.flag_return_in_progress;
7024 /* "we are inside sourced file, ok to use return" */
7025 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007026#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007027 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007028
Denis Vlasenkob6e65562009-04-03 16:49:04 +00007029 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007030 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00007031
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007032 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00007033#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007034 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00007035#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007036
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00007037 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007038}
7039
7040static int builtin_umask(char **argv)
7041{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007042 int rc;
7043 mode_t mask;
7044
7045 mask = umask(0);
7046 if (argv[1]) {
7047 mode_t old_mask = mask;
7048
7049 mask ^= 0777;
7050 rc = bb_parse_mode(argv[1], &mask);
7051 mask ^= 0777;
7052 if (rc == 0) {
7053 mask = old_mask;
7054 /* bash messages:
7055 * bash: umask: 'q': invalid symbolic mode operator
7056 * bash: umask: 999: octal number out of range
7057 */
7058 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007059 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007060 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007061 rc = 1;
7062 /* Mimic bash */
7063 printf("%04o\n", (unsigned) mask);
7064 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007065 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00007066 umask(mask);
7067
7068 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007069}
7070
Mike Frysingerd690f682009-03-30 06:50:54 +00007071/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007072static int builtin_unset(char **argv)
7073{
Mike Frysingerd690f682009-03-30 06:50:54 +00007074 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00007075 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00007076
Denis Vlasenko28e67962009-04-26 23:22:40 +00007077 /* "!": do not abort on errors */
7078 /* "+": stop at 1st non-option */
7079 opts = getopt32(argv, "!+vf");
7080 if (opts == (unsigned)-1)
7081 return EXIT_FAILURE;
7082 if (opts == 3) {
7083 bb_error_msg("unset: -v and -f are exclusive");
7084 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00007085 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00007086 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00007087
7088 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007089 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00007090 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007091 if (unset_local_var(*argv)) {
7092 /* unset <nonexistent_var> doesn't fail.
7093 * Error is when one tries to unset RO var.
7094 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00007095 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007096 }
Mike Frysingerd690f682009-03-30 06:50:54 +00007097 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00007098#if ENABLE_HUSH_FUNCTIONS
7099 else {
7100 unset_func(*argv);
7101 }
7102#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00007103 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00007104 }
7105 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00007106}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007107
Mike Frysinger56bdea12009-03-28 20:01:58 +00007108/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
7109static int builtin_wait(char **argv)
7110{
7111 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007112 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007113
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007114 if (*++argv == NULL) {
7115 /* Don't care about wait results */
7116 /* Note 1: must wait until there are no more children */
7117 /* Note 2: must be interruptible */
7118 /* Examples:
7119 * $ sleep 3 & sleep 6 & wait
7120 * [1] 30934 sleep 3
7121 * [2] 30935 sleep 6
7122 * [1] Done sleep 3
7123 * [2] Done sleep 6
7124 * $ sleep 3 & sleep 6 & wait
7125 * [1] 30936 sleep 3
7126 * [2] 30937 sleep 6
7127 * [1] Done sleep 3
7128 * ^C <-- after ~4 sec from keyboard
7129 * $
7130 */
7131 sigaddset(&G.blocked_set, SIGCHLD);
7132 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7133 while (1) {
7134 checkjobs(NULL);
7135 if (errno == ECHILD)
7136 break;
7137 /* Wait for SIGCHLD or any other signal of interest */
7138 /* sigtimedwait with infinite timeout: */
7139 sig = sigwaitinfo(&G.blocked_set, NULL);
7140 if (sig > 0) {
7141 sig = check_and_run_traps(sig);
7142 if (sig && sig != SIGCHLD) { /* see note 2 */
7143 ret = 128 + sig;
7144 break;
7145 }
7146 }
7147 }
7148 sigdelset(&G.blocked_set, SIGCHLD);
7149 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7150 return ret;
7151 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007152
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007153 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007154 while (*argv) {
7155 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007156 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007157 /* mimic bash message */
7158 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007159 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007160 }
7161 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007162 if (WIFSIGNALED(status))
7163 ret = 128 + WTERMSIG(status);
7164 else if (WIFEXITED(status))
7165 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007166 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007167 ret = EXIT_FAILURE;
7168 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007169 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007170 ret = 127;
7171 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007172 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007173 }
7174
7175 return ret;
7176}
7177
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007178#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7179static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7180{
7181 if (argv[1]) {
7182 def = bb_strtou(argv[1], NULL, 10);
7183 if (errno || def < def_min || argv[2]) {
7184 bb_error_msg("%s: bad arguments", argv[0]);
7185 def = UINT_MAX;
7186 }
7187 }
7188 return def;
7189}
7190#endif
7191
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007192#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00007193static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007194{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007195 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007196 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007197 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007198 return EXIT_SUCCESS; /* bash compat */
7199 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007200 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007201
7202 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7203 if (depth == UINT_MAX)
7204 G.flag_break_continue = BC_BREAK;
7205 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007206 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007207
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007208 return EXIT_SUCCESS;
7209}
7210
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00007211static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007212{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007213 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7214 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007215}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007216#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007217
7218#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko7b9e5c52009-04-17 23:53:15 +00007219static int builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007220{
7221 int rc;
7222
7223 if (G.flag_return_in_progress != -1) {
7224 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7225 return EXIT_FAILURE; /* bash compat */
7226 }
7227
7228 G.flag_return_in_progress = 1;
7229
7230 /* bash:
7231 * out of range: wraps around at 256, does not error out
7232 * non-numeric param:
7233 * f() { false; return qwe; }; f; echo $?
7234 * bash: return: qwe: numeric argument required <== we do this
7235 * 255 <== we also do this
7236 */
7237 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7238 return rc;
7239}
7240#endif