blob: 9c2c0f3240828b0eae8d6f18f8c205d8038f822e [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)
Eric Andersen83a2ae22001-05-07 17:59:25 +000053 * change { and } from special chars to reserved words
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000054 * builtins: return, 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 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000057 * continuation lines, both explicit and implicit - done?
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000058 * SIGHUP handling
59 * ^Z handling (and explain it in comments for mere humans)
60 * separate job control from interactiveness
61 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
Eric Andersen25f27032001-04-26 23:22:31 +000062 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000063 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000064 */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000065#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000066#include <glob.h>
67/* #include <dmalloc.h> */
68#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000069# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000070#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000071#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000072#include "match.h"
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000073#ifndef PIPE_BUF
74# define PIPE_BUF 4096 /* amount of buffering in a pipe */
75#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000076
Denis Vlasenko1943aec2009-04-09 14:15:57 +000077
78/* Debug build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000079#define LEAK_HUNTING 0
80#define BUILD_AS_NOMMU 0
81/* Enable/disable sanity checks. Ok to enable in production,
82 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
83 * Keeping 1 for now even in released versions.
84 */
85#define HUSH_DEBUG 1
86/* In progress... */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +000087#define ENABLE_HUSH_FUNCTIONS 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +000088
89
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000090#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +000091# undef BB_MMU
92# undef USE_FOR_NOMMU
93# undef USE_FOR_MMU
94# define BB_MMU 0
95# define USE_FOR_NOMMU(...) __VA_ARGS__
96# define USE_FOR_MMU(...)
97#endif
98
Denis Vlasenko61befda2008-11-25 01:36:03 +000099#if defined SINGLE_APPLET_MAIN
100/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000101# undef CONFIG_FEATURE_SH_STANDALONE
102# undef ENABLE_FEATURE_SH_STANDALONE
103# undef USE_FEATURE_SH_STANDALONE
104# define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
105# define ENABLE_FEATURE_SH_STANDALONE 0
106# define USE_FEATURE_SH_STANDALONE(...)
107# define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000108#endif
109
Denis Vlasenko05743d72008-02-10 12:10:08 +0000110#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000111# undef ENABLE_FEATURE_EDITING
112# define ENABLE_FEATURE_EDITING 0
113# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
114# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000115#endif
116
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000117/* Do we support ANY keywords? */
118#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000119# define HAS_KEYWORDS 1
120# define IF_HAS_KEYWORDS(...) __VA_ARGS__
121# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000122#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000123# define HAS_KEYWORDS 0
124# define IF_HAS_KEYWORDS(...)
125# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000126#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000127
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000128/* If you comment out one of these below, it will be #defined later
129 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000130#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000131/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000132#define debug_printf_parse(...) do {} while (0)
133#define debug_print_tree(a, b) do {} while (0)
134#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000135#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000136#define debug_printf_jobs(...) do {} while (0)
137#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000138#define debug_printf_glob(...) do {} while (0)
139#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000140#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000141#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000142
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000143#define ERR_PTR ((void*)(long)1)
144
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000145#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000146
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000147#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000148
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000149static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
150
151/* This supports saving pointers malloced in vfork child,
152 * to be freed in the parent. One pointer is saved in
153 * G.argv_from_re_execing global var instead. TODO: unify.
154 */
155#if !BB_MMU
156typedef struct nommu_save_t {
157 char **new_env;
158 char **old_env;
159 char **argv;
160} nommu_save_t;
161#endif
162
Denis Vlasenko55789c62008-06-18 16:30:42 +0000163/* The descrip member of this structure is only used to make
164 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000165static const struct {
166 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000167 signed char default_fd;
168 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000169} redir_table[] = {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000170 { 0, 0, "??" },
Eric Andersen25f27032001-04-26 23:22:31 +0000171 { O_RDONLY, 0, "<" },
172 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
173 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000174 { O_RDONLY, 0, "<<" },
175 { O_CREAT|O_RDWR, 1, "<>" },
176/* Should not be needed. Bogus default_fd helps in debugging */
177/* { O_RDONLY, 77, "<<" }, */
Eric Andersen25f27032001-04-26 23:22:31 +0000178};
179
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000180typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000181 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000182#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000183 RES_IF ,
184 RES_THEN ,
185 RES_ELIF ,
186 RES_ELSE ,
187 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000188#endif
189#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000190 RES_FOR ,
191 RES_WHILE ,
192 RES_UNTIL ,
193 RES_DO ,
194 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000195#endif
196#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000197 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000198#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000199#if ENABLE_HUSH_CASE
200 RES_CASE ,
201 /* two pseudo-keywords support contrived "case" syntax: */
202 RES_MATCH , /* "word)" */
203 RES_CASEI , /* "this command is inside CASE" */
204 RES_ESAC ,
205#endif
206 RES_XXXX ,
207 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000208} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000209
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000210typedef struct o_string {
211 char *data;
212 int length; /* position where data is appended */
213 int maxlen;
214 /* Protect newly added chars against globbing
215 * (by prepending \ to *, ?, [, \) */
216 smallint o_escape;
217 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000218 /* At least some part of the string was inside '' or "",
219 * possibly empty one: word"", wo''rd etc. */
220 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000221 smallint has_empty_slot;
222 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
223} o_string;
224enum {
225 MAYBE_ASSIGNMENT = 0,
226 DEFINITELY_ASSIGNMENT = 1,
227 NOT_ASSIGNMENT = 2,
228 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
229};
230/* Used for initialization: o_string foo = NULL_O_STRING; */
231#define NULL_O_STRING { NULL }
232
233/* I can almost use ordinary FILE*. Is open_memstream() universally
234 * available? Where is it documented? */
235typedef struct in_str {
236 const char *p;
237 /* eof_flag=1: last char in ->p is really an EOF */
238 char eof_flag; /* meaningless if ->p == NULL */
239 char peek_buf[2];
240#if ENABLE_HUSH_INTERACTIVE
241 smallint promptme;
242 smallint promptmode; /* 0: PS1, 1: PS2 */
243#endif
244 FILE *file;
245 int (*get) (struct in_str *);
246 int (*peek) (struct in_str *);
247} in_str;
248#define i_getch(input) ((input)->get(input))
249#define i_peek(input) ((input)->peek(input))
250
Eric Andersen25f27032001-04-26 23:22:31 +0000251struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000252 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000253 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000254 int rd_fd; /* fd to redirect */
255 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
256 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000257 smallint rd_type; /* (enum redir_type) */
258 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000259 * and subsequently heredoc itself; and rd_dup is a bitmask:
260 * 1: do we need to trim leading tabs?
Denis Vlasenkoed055212009-04-11 10:37:10 +0000261 * 2: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000262 */
Eric Andersen25f27032001-04-26 23:22:31 +0000263};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000264typedef enum redir_type {
265 REDIRECT_INVALID = 0,
266 REDIRECT_INPUT = 1,
267 REDIRECT_OVERWRITE = 2,
268 REDIRECT_APPEND = 3,
269 REDIRECT_HEREDOC = 4,
270 REDIRECT_IO = 5,
271 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000272
273 REDIRFD_CLOSE = -3,
274 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000275 REDIRFD_TO_FILE = -1,
276 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000277
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000278 HEREDOC_SKIPTABS = 1,
279 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000280} redir_type;
281
Eric Andersen25f27032001-04-26 23:22:31 +0000282
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000283struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000284 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000285 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000286 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000287 smallint grp_type; /* GRP_xxx */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000288#define GRP_NORMAL 0
289#define GRP_SUBSHELL 1
290#if ENABLE_HUSH_FUNCTIONS
291# define GRP_FUNCTION 2
292#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000293 struct pipe *group; /* if non-NULL, this "command" is { list },
294 * ( list ), or a compound statement */
295#if !BB_MMU
296 char *group_as_string;
297#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000298#if ENABLE_HUSH_FUNCTIONS
299 struct function *child_func;
300/* This field is used to prevent a bug here:
301 * while...do f1() {a;}; f1; f1 {b;}; f1; done
302 * When we execute "f1() {a;}" cmd, we create new function and clear
303 * cmd->group, cmd->group_as_string, cmd->argv[0].
304 * when we execute "f1 {b;}", we notice that f1 exists,
305 * and that it's "parent cmd" struct is still "alive",
306 * we put those fields back into cmd->xxx
307 * (struct function has ->parent_cmd ptr to facilitate that).
308 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
309 * Without this trick, loop would execute a;b;b;b;...
310 * instead of correct sequence a;b;a;b;...
311 * When command is freed, it severs the link
312 * (sets ->child_func->parent_cmd to NULL).
313 */
314#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000315 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000316/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
317 * and on execution these are substituted with their values.
318 * Substitution can make _several_ words out of one argv[n]!
319 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000320 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000321 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000322 struct redir_struct *redirects; /* I/O redirections */
323};
Eric Andersen25f27032001-04-26 23:22:31 +0000324
325struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000326 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000327 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000328 int alive_cmds; /* number of commands running (not exited) */
329 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000330#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000331 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000332 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000333 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000334#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000335 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000336 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000337 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
338 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000339};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000340typedef enum pipe_style {
341 PIPE_SEQ = 1,
342 PIPE_AND = 2,
343 PIPE_OR = 3,
344 PIPE_BG = 4,
345} pipe_style;
Eric Andersen25f27032001-04-26 23:22:31 +0000346
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000347/* This holds pointers to the various results of parsing */
348struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000349 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000350 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000351 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000352 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000353 /* last command in pipe (being constructed right now) */
354 struct command *command;
355 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000356 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000357#if !BB_MMU
358 o_string as_string;
359#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000360#if HAS_KEYWORDS
361 smallint ctx_res_w;
362 smallint ctx_inverted; /* "! cmd | cmd" */
363#if ENABLE_HUSH_CASE
364 smallint ctx_dsemicolon; /* ";;" seen */
365#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000366 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
367 int old_flag;
368 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000369 * example: "if pipe1; pipe2; then pipe3; fi"
370 * when we see "if" or "then", we malloc and copy current context,
371 * and make ->stack point to it. then we parse pipeN.
372 * when closing "then" / fi" / whatever is found,
373 * we move list_head into ->stack->command->group,
374 * copy ->stack into current context, and delete ->stack.
375 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000376 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000377 struct parse_context *stack;
378#endif
379};
380
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000381/* On program start, environ points to initial environment.
382 * putenv adds new pointers into it, unsetenv removes them.
383 * Neither of these (de)allocates the strings.
384 * setenv allocates new strings in malloc space and does putenv,
385 * and thus setenv is unusable (leaky) for shell's purposes */
386#define setenv(...) setenv_is_leaky_dont_use()
387struct variable {
388 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000389 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000390 int max_len; /* if > 0, name is part of initial env; else name is malloced */
391 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000392 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000393};
394
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000395enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000396 BC_BREAK = 1,
397 BC_CONTINUE = 2,
398};
399
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000400#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000401struct function {
402 struct function *next;
403 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000404 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000405 struct pipe *body;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000406#if !BB_MMU
407 char *body_as_string;
408#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000409};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000410#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000411
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000412
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000413/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000414/* Sorted roughly by size (smaller offsets == smaller code) */
415struct globals {
416#if ENABLE_HUSH_INTERACTIVE
417 /* 'interactive_fd' is a fd# open to ctty, if we have one
418 * _AND_ if we decided to act interactively */
419 int interactive_fd;
420 const char *PS1;
421 const char *PS2;
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000422#define G_interactive_fd (G.interactive_fd)
423#else
424#define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000425#endif
426#if ENABLE_FEATURE_EDITING
427 line_input_t *line_input_state;
428#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000429 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000430 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000431#if ENABLE_HUSH_JOB
432 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000433 pid_t saved_tty_pgrp;
434 int last_jobid;
435 struct pipe *job_list;
436 struct pipe *toplevel_list;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000437//// smallint ctrl_z_flag;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000438#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000439 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000440#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000441 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000442#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000443 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000444 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000445 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000446 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000447 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000448 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000449 /* how many non-NULL argv's we have. NB: $# + 1 */
450 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000451 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000452#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000453 char *argv0_for_re_execing;
454 char **argv_from_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000455#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000456#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000457 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000458 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000459#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000460 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000461 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000462 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000463 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000464#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000465 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000466#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000467 /* Signal and trap handling */
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000468// unsigned count_SIGCHLD;
469// unsigned handled_SIGCHLD;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000470 /* which signals have non-DFL handler (even with no traps set)? */
471 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000472 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000473 sigset_t blocked_set;
474 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000475#if HUSH_DEBUG
476 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000477 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000478#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000479 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
480#if ENABLE_FEATURE_SH_STANDALONE
481 struct nofork_save_area nofork_save;
482#endif
483#if ENABLE_HUSH_JOB
484 sigjmp_buf toplevel_jb;
485#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000486};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000487#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000488/* Not #defining name to G.name - this quickly gets unwieldy
489 * (too many defines). Also, I actually prefer to see when a variable
490 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000491#define INIT_G() do { \
492 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
493} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000494
495
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000496/* Function prototypes for builtins */
497static int builtin_cd(char **argv);
498static int builtin_echo(char **argv);
499static int builtin_eval(char **argv);
500static int builtin_exec(char **argv);
501static int builtin_exit(char **argv);
502static int builtin_export(char **argv);
503#if ENABLE_HUSH_JOB
504static int builtin_fg_bg(char **argv);
505static int builtin_jobs(char **argv);
506#endif
507#if ENABLE_HUSH_HELP
508static int builtin_help(char **argv);
509#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000510#if HUSH_DEBUG
511static int builtin_memleak(char **argv);
512#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000513static int builtin_pwd(char **argv);
514static int builtin_read(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000515static int builtin_set(char **argv);
516static int builtin_shift(char **argv);
517static int builtin_source(char **argv);
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000518static int builtin_test(char **argv);
519static int builtin_trap(char **argv);
520static int builtin_true(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000521static int builtin_umask(char **argv);
522static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000523static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000524#if ENABLE_HUSH_LOOPS
525static int builtin_break(char **argv);
526static int builtin_continue(char **argv);
527#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000528
529/* Table of built-in functions. They can be forked or not, depending on
530 * context: within pipes, they fork. As simple commands, they do not.
531 * When used in non-forking context, they can change global variables
532 * in the parent shell process. If forked, of course they cannot.
533 * For example, 'unset foo | whatever' will parse and run, but foo will
534 * still be set at the end. */
535struct built_in_command {
536 const char *cmd;
537 int (*function)(char **argv);
538#if ENABLE_HUSH_HELP
539 const char *descr;
540#define BLTIN(cmd, func, help) { cmd, func, help }
541#else
542#define BLTIN(cmd, func, help) { cmd, func }
543#endif
544};
545
546/* For now, echo and test are unconditionally enabled.
547 * Maybe make it configurable? */
548static const struct built_in_command bltins[] = {
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000549 BLTIN("." , builtin_source , "Run commands in a file"),
550 BLTIN(":" , builtin_true , "No-op"),
551 BLTIN("[" , builtin_test , "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000552#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000553 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000554#endif
555#if ENABLE_HUSH_LOOPS
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000556 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000557#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000558 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000559#if ENABLE_HUSH_LOOPS
560 BLTIN("continue", builtin_continue, "Start new loop iteration"),
561#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000562 BLTIN("echo" , builtin_echo , "Write to stdout"),
563 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
564 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
565 BLTIN("exit" , builtin_exit , "Exit"),
566 BLTIN("export" , builtin_export , "Set environment variable"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000567#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000568 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000569#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000570#if ENABLE_HUSH_HELP
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000571 BLTIN("help" , builtin_help , "List shell built-in commands"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000572#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000573#if ENABLE_HUSH_JOB
574 BLTIN("jobs" , builtin_jobs , "List active jobs"),
575#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000576#if HUSH_DEBUG
577 BLTIN("memleak" , builtin_memleak , "Debug tool"),
578#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000579 BLTIN("pwd" , builtin_pwd , "Print current directory"),
580 BLTIN("read" , builtin_read , "Input environment variable"),
581// BLTIN("return" , builtin_return , "Return from a function"),
582 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
583 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
584 BLTIN("test" , builtin_test , "Test condition"),
585 BLTIN("trap" , builtin_trap , "Trap signals"),
586// BLTIN("ulimit" , builtin_return , "Control resource limits"),
587 BLTIN("umask" , builtin_umask , "Set file creation mask"),
588 BLTIN("unset" , builtin_unset , "Unset environment variable"),
589 BLTIN("wait" , builtin_wait , "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000590};
591
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000592
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000593/* Debug printouts.
594 */
595#if HUSH_DEBUG
596/* prevent disasters with G.debug_indent < 0 */
597# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
598# define debug_enter() (G.debug_indent++)
599# define debug_leave() (G.debug_indent--)
600#else
601# define indent() ((void)0)
602# define debug_enter() ((void)0)
603# define debug_leave() ((void)0)
604#endif
605
606#ifndef debug_printf
607# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
608#endif
609
610#ifndef debug_printf_parse
611# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
612#endif
613
614#ifndef debug_printf_exec
615#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
616#endif
617
618#ifndef debug_printf_env
619# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
620#endif
621
622#ifndef debug_printf_jobs
623# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
624# define DEBUG_JOBS 1
625#else
626# define DEBUG_JOBS 0
627#endif
628
629#ifndef debug_printf_expand
630# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
631# define DEBUG_EXPAND 1
632#else
633# define DEBUG_EXPAND 0
634#endif
635
636#ifndef debug_printf_glob
637# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
638# define DEBUG_GLOB 1
639#else
640# define DEBUG_GLOB 0
641#endif
642
643#ifndef debug_printf_list
644# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
645#endif
646
647#ifndef debug_printf_subst
648# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
649#endif
650
651#ifndef debug_printf_clean
652# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
653# define DEBUG_CLEAN 1
654#else
655# define DEBUG_CLEAN 0
656#endif
657
658#if DEBUG_EXPAND
659static void debug_print_strings(const char *prefix, char **vv)
660{
661 indent();
662 fprintf(stderr, "%s:\n", prefix);
663 while (*vv)
664 fprintf(stderr, " '%s'\n", *vv++);
665}
666#else
667#define debug_print_strings(prefix, vv) ((void)0)
668#endif
669
670
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000671/* Leak hunting. Use hush_leaktool.sh for post-processing.
672 */
673#if LEAK_HUNTING
674static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000675{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000676 void *ptr = xmalloc((size + 0xff) & ~0xff);
677 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
678 return ptr;
679}
680static void *xxrealloc(int lineno, void *ptr, size_t size)
681{
682 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
683 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
684 return ptr;
685}
686static char *xxstrdup(int lineno, const char *str)
687{
688 char *ptr = xstrdup(str);
689 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
690 return ptr;
691}
692static void xxfree(void *ptr)
693{
694 fdprintf(2, "free %p\n", ptr);
695 free(ptr);
696}
697#define xmalloc(s) xxmalloc(__LINE__, s)
698#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
699#define xstrdup(s) xxstrdup(__LINE__, s)
700#define free(p) xxfree(p)
701#endif
702
703
704/* Syntax and runtime errors. They always abort scripts.
705 * In interactive use they usually discard unparsed and/or unexecuted commands
706 * and return to the prompt.
707 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
708 */
709#if HUSH_DEBUG < 2
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000710# define die_if_script(lineno, fmt...) die_if_script(fmt)
711# define syntax_error(lineno, msg) syntax_error(msg)
712# define syntax_error_at(lineno, msg) syntax_error_at(msg)
713# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
714# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
715# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000716#endif
717
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000718static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000719{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000720 va_list p;
721
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000722#if HUSH_DEBUG >= 2
723 bb_error_msg("hush.c:%u", lineno);
724#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000725 va_start(p, fmt);
726 bb_verror_msg(fmt, p, NULL);
727 va_end(p);
728 if (!G_interactive_fd)
729 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000730}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000731
732static void syntax_error(unsigned lineno, const char *msg)
733{
734 if (msg)
735 die_if_script(lineno, "syntax error: %s", msg);
736 else
737 die_if_script(lineno, "syntax error", NULL);
738}
739
740static void syntax_error_at(unsigned lineno, const char *msg)
741{
742 die_if_script(lineno, "syntax error at '%s'", msg);
743}
744
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000745/* It so happens that all such cases are totally fatal
746 * even if shell is interactive: EOF while looking for closing
747 * delimiter. There is nowhere to read stuff from after that,
748 * it's EOF! The only choice is to terminate.
749 */
750static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000751static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000752{
753 char msg[2];
754 msg[0] = ch;
755 msg[1] = '\0';
756 die_if_script(lineno, "syntax error: unterminated %s", msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000757 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000758}
759
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000760static void syntax_error_unterm_str(unsigned lineno, const char *s)
761{
762 die_if_script(lineno, "syntax error: unterminated %s", s);
763}
764
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000765static void syntax_error_unexpected_ch(unsigned lineno, char ch)
766{
767 char msg[2];
768 msg[0] = ch;
769 msg[1] = '\0';
770 die_if_script(lineno, "syntax error: unexpected %s", msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000771}
772
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000773#if HUSH_DEBUG < 2
774# undef die_if_script
775# undef syntax_error
776# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000777# undef syntax_error_unterm_ch
778# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000779# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000780#else
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000781# define die_if_script(fmt...) die_if_script(__LINE__, fmt)
782# define syntax_error(msg) syntax_error(__LINE__, msg)
783# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
784# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
785# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
786# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000787#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000788
Denis Vlasenko552433b2009-04-04 19:29:21 +0000789
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000790/* Utility functions
791 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000792static int glob_needed(const char *s)
793{
794 while (*s) {
795 if (*s == '\\')
796 s++;
797 if (*s == '*' || *s == '[' || *s == '?')
798 return 1;
799 s++;
800 }
801 return 0;
802}
803
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000804static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000805{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000806 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000807 return 0;
808 s++;
809 while (isalnum(*s) || *s == '_')
810 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000811 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000812}
813
Denis Vlasenko55789c62008-06-18 16:30:42 +0000814/* Replace each \x with x in place, return ptr past NUL. */
815static char *unbackslash(char *src)
816{
817 char *dst = src;
818 while (1) {
819 if (*src == '\\')
820 src++;
821 if ((*dst++ = *src++) == '\0')
822 break;
823 }
824 return dst;
825}
826
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000827static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000828{
829 int i;
830 unsigned count1;
831 unsigned count2;
832 char **v;
833
834 v = strings;
835 count1 = 0;
836 if (v) {
837 while (*v) {
838 count1++;
839 v++;
840 }
841 }
842 count2 = 0;
843 v = add;
844 while (*v) {
845 count2++;
846 v++;
847 }
848 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
849 v[count1 + count2] = NULL;
850 i = count2;
851 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000852 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000853 return v;
854}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000855#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000856static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
857{
858 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
859 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
860 return ptr;
861}
862#define add_strings_to_strings(strings, add, need_to_dup) \
863 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
864#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000865
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000866static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000867{
868 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000869 v[0] = add;
870 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000871 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000872}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000873#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000874static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
875{
876 char **ptr = add_string_to_strings(strings, add);
877 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
878 return ptr;
879}
880#define add_string_to_strings(strings, add) \
881 xx_add_string_to_strings(__LINE__, strings, add)
882#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000883
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000884static void putenv_all(char **strings)
885{
886 if (!strings)
887 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000888 while (*strings) {
889 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000890 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000891 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000892}
893
894static char **putenv_all_and_save_old(char **strings)
895{
896 char **old = NULL;
897 char **s = strings;
898
899 if (!strings)
900 return old;
901 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000902 char *v, *eq;
903
904 eq = strchr(*strings, '=');
905 if (eq) {
906 *eq = '\0';
907 v = getenv(*strings);
908 *eq = '=';
909 if (v) {
910 /* v points to VAL in VAR=VAL, go back to VAR */
911 v -= (eq - *strings) + 1;
912 old = add_string_to_strings(old, v);
913 }
914 }
915 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000916 }
917 putenv_all(s);
918 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000919}
920
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000921static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000922{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000923 char **v;
924
925 if (!strings)
926 return;
927
928 v = strings;
929 while (*v) {
930 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000931 debug_printf_env("unsetenv '%s'\n", *v);
932 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000933 }
934 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000935 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000936 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000937}
938
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000939static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000940{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000941 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000942}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000943
944
Denis Vlasenkod5762932009-03-31 11:22:57 +0000945/* Basic theory of signal handling in shell
946 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000947 * This does not describe what hush does, rather, it is current understanding
948 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000949 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
950 *
951 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
952 * is finished or backgrounded. It is the same in interactive and
953 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000954 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000955 * ^C or ^Z from keyboard seem to execute "at once" because it usually
956 * backgrounds (i.e. stops) or kills all members of currently running
957 * pipe.
958 *
959 * Wait builtin in interruptible by signals for which user trap is set
960 * or by SIGINT in interactive shell.
961 *
962 * Trap handlers will execute even within trap handlers. (right?)
963 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000964 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000965 *
966 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000967 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000968 *
969 * Commands run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000970 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000971 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000972 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
973 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000974 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000975 * Siganls which differ from SIG_DFL action
976 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +0000977 *
978 * SIGQUIT: ignore
979 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000980 * SIGHUP (interactive):
981 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +0000982 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000983 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
984 * that all pipe members are stopped) (right?)
Denis Vlasenkod5762932009-03-31 11:22:57 +0000985 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000986 * of the command line, show prompt. NB: ^C does not send SIGINT
987 * to interactive shell while shell is waiting for a pipe,
988 * since shell is bg'ed (is not in foreground process group).
989 * (check/expand this)
990 * Example 1: this waits 5 sec, but does not execute ls:
991 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
992 * Example 2: this does not wait and does not execute ls:
993 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
994 * Example 3: this does not wait 5 sec, but executes ls:
995 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +0000996 *
997 * (What happens to signals which are IGN on shell start?)
998 * (What happens with signal mask on shell start?)
999 *
1000 * Implementation in hush
1001 * ======================
1002 * We use in-kernel pending signal mask to determine which signals were sent.
1003 * We block all signals which we don't want to take action immediately,
1004 * i.e. we block all signals which need to have special handling as described
1005 * above, and all signals which have traps set.
1006 * After each pipe execution, we extract any pending signals via sigtimedwait()
1007 * and act on them.
1008 *
1009 * unsigned non_DFL_mask: a mask of such "special" signals
1010 * sigset_t blocked_set: current blocked signal set
1011 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001012 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001013 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001014 * "trap 'cmd' SIGxxx":
1015 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001016 * after [v]fork, if we plan to be a shell:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001017 * nothing for {} child shell (say, "true | { true; true; } | true")
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001018 * unset all traps if () shell.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001019 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001020 * POSIX says pending signal mask is cleared in child - no need to clear it.
1021 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001022 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001023 * Note: as a result, we do not use signal handlers much. The only uses
1024 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
1025 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001026 */
1027
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001028//static void SIGCHLD_handler(int sig UNUSED_PARAM)
1029//{
1030// G.count_SIGCHLD++;
1031//}
1032
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001033static int check_and_run_traps(int sig)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001034{
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001035 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenkod5762932009-03-31 11:22:57 +00001036 smalluint save_rcode;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001037 int last_sig = 0;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001038
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001039 if (sig)
1040 goto jump_in;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001041 while (1) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001042 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001043 if (sig <= 0)
1044 break;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001045 jump_in:
1046 last_sig = sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001047 if (G.traps && G.traps[sig]) {
1048 if (G.traps[sig][0]) {
1049 /* We have user-defined handler */
1050 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001051 save_rcode = G.last_exitcode;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001052 builtin_eval(argv);
1053 free(argv[1]);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001054 G.last_exitcode = save_rcode;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001055 } /* else: "" trap, ignoring signal */
1056 continue;
1057 }
1058 /* not a trap: special action */
Denis Vlasenkod5762932009-03-31 11:22:57 +00001059 switch (sig) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001060// case SIGCHLD:
1061// G.count_SIGCHLD++;
1062// break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001063 case SIGINT:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001064 bb_putchar('\n');
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001065 G.flag_SIGINT = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001066 break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001067//TODO
1068// case SIGHUP: ...
1069// break;
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00001070 default: /* ignored: */
1071 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001072 break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001073 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00001074 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001075 return last_sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001076}
1077
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001078#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001079
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001080/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1081#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001082/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001083#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1084
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001085/* Restores tty foreground process group, and exits.
1086 * May be called as signal handler for fatal signal
1087 * (will faithfully resend signal to itself, producing correct exit state)
1088 * or called directly with -EXITCODE.
1089 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001090static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001091static void sigexit(int sig)
1092{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001093 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001094 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001095
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001096 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001097 * tty pgrp then, only top-level shell process does that */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001098 if (G_interactive_fd && getpid() == G.root_pid)
1099 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001100
1101 /* Not a signal, just exit */
1102 if (sig <= 0)
1103 _exit(- sig);
1104
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001105 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001106}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001107#else
1108
1109#define disable_restore_tty_pgrp_on_exit() ((void)0)
1110#define enable_restore_tty_pgrp_on_exit() ((void)0)
1111
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001112#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001113
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001114/* Restores tty foreground process group, and exits. */
1115static void hush_exit(int exitcode) NORETURN;
1116static void hush_exit(int exitcode)
1117{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001118 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1119 /* Prevent recursion:
1120 * trap "echo Hi; exit" EXIT; exit
1121 */
1122 char *argv[] = { NULL, G.traps[0], NULL };
1123 G.traps[0] = NULL;
1124 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001125 builtin_eval(argv);
1126 free(argv[1]);
1127 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001128
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001129#if ENABLE_HUSH_JOB
1130 fflush(NULL); /* flush all streams */
1131 sigexit(- (exitcode & 0xff));
1132#else
1133 exit(exitcode);
1134#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001135}
1136
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001137
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001138static const char *set_cwd(void)
1139{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001140 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1141 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001142 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001143 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001144 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1145 if (!G.cwd)
1146 G.cwd = bb_msg_unknown;
1147 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001148}
1149
Denis Vlasenko83506862007-11-23 13:11:42 +00001150
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001151/* Get/check local shell variables */
1152static struct variable *get_local_var(const char *name)
1153{
1154 struct variable *cur;
1155 int len;
1156
1157 if (!name)
1158 return NULL;
1159 len = strlen(name);
1160 for (cur = G.top_var; cur; cur = cur->next) {
1161 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1162 return cur;
1163 }
1164 return NULL;
1165}
1166
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001167static const char *get_local_var_value(const char *src)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001168{
1169 struct variable *var = get_local_var(src);
1170 if (var)
1171 return strchr(var->varstr, '=') + 1;
1172 return NULL;
1173}
1174
1175/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001176 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001177 * flg_export:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001178 * 0: do not export
1179 * 1: export
1180 * -1: if NAME is set, leave export status alone
1181 * if NAME is not set, do not export
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001182 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001183 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001184#if BB_MMU
1185#define set_local_var(str, flg_export, flg_read_only) \
1186 set_local_var(str, flg_export)
1187#endif
1188static int set_local_var(char *str, int flg_export, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001189{
1190 struct variable *cur;
1191 char *value;
1192 int name_len;
1193
1194 value = strchr(str, '=');
1195 if (!value) { /* not expected to ever happen? */
1196 free(str);
1197 return -1;
1198 }
1199
1200 name_len = value - str + 1; /* including '=' */
1201 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1202 while (1) {
1203 if (strncmp(cur->varstr, str, name_len) != 0) {
1204 if (!cur->next) {
1205 /* Bail out. Note that now cur points
1206 * to last var in linked list */
1207 break;
1208 }
1209 cur = cur->next;
1210 continue;
1211 }
1212 /* We found an existing var with this name */
1213 *value = '\0';
1214 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001215#if !BB_MMU
1216 if (!flg_read_only)
1217#endif
1218 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001219 free(str);
1220 return -1;
1221 }
1222 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1223 unsetenv(str); /* just in case */
1224 *value = '=';
1225 if (strcmp(cur->varstr, str) == 0) {
1226 free_and_exp:
1227 free(str);
1228 goto exp;
1229 }
1230 if (cur->max_len >= strlen(str)) {
1231 /* This one is from startup env, reuse space */
1232 strcpy(cur->varstr, str);
1233 goto free_and_exp;
1234 }
1235 /* max_len == 0 signifies "malloced" var, which we can
1236 * (and has to) free */
1237 if (!cur->max_len)
1238 free(cur->varstr);
1239 cur->max_len = 0;
1240 goto set_str_and_exp;
1241 }
1242
1243 /* Not found - create next variable struct */
1244 cur->next = xzalloc(sizeof(*cur));
1245 cur = cur->next;
1246
1247 set_str_and_exp:
1248 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001249#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001250 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001251#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001252 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001253 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001254 cur->flg_export = 1;
1255 if (cur->flg_export) {
1256 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1257 return putenv(cur->varstr);
1258 }
1259 return 0;
1260}
1261
Mike Frysingerd690f682009-03-30 06:50:54 +00001262static int unset_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001263{
1264 struct variable *cur;
1265 struct variable *prev = prev; /* for gcc */
1266 int name_len;
1267
1268 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001269 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001270 name_len = strlen(name);
1271 cur = G.top_var;
1272 while (cur) {
1273 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1274 if (cur->flg_read_only) {
1275 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001276 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001277 }
1278 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1279 * is ro, and we cannot reach this code on the 1st pass */
1280 prev->next = cur->next;
1281 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1282 bb_unsetenv(cur->varstr);
1283 if (!cur->max_len)
1284 free(cur->varstr);
1285 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001286 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001287 }
1288 prev = cur;
1289 cur = cur->next;
1290 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001291 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001292}
1293
Mike Frysinger98c52642009-04-02 10:02:37 +00001294#if ENABLE_SH_MATH_SUPPORT
1295#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1296#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1297static char *endofname(const char *name)
1298{
1299 char *p;
1300
1301 p = (char *) name;
1302 if (!is_name(*p))
1303 return p;
1304 while (*++p) {
1305 if (!is_in_name(*p))
1306 break;
1307 }
1308 return p;
1309}
1310
1311static void arith_set_local_var(const char *name, const char *val, int flags)
1312{
1313 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001314 char *var = xasprintf("%s=%s", name, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001315 set_local_var(var, flags, 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001316}
1317#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001318
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001319
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001320/*
1321 * in_str support
1322 */
1323static int static_get(struct in_str *i)
1324{
1325 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001326 if (ch != '\0')
1327 return ch;
1328 i->p--;
1329 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001330}
1331
1332static int static_peek(struct in_str *i)
1333{
1334 return *i->p;
1335}
1336
1337#if ENABLE_HUSH_INTERACTIVE
1338
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001339static void cmdedit_set_initial_prompt(void)
1340{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001341 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1342 G.PS1 = getenv("PS1");
1343 if (G.PS1 == NULL)
1344 G.PS1 = "\\w \\$ ";
1345 } else
1346 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001347}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001348
1349static const char* setup_prompt_string(int promptmode)
1350{
1351 const char *prompt_str;
1352 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001353 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1354 /* Set up the prompt */
1355 if (promptmode == 0) { /* PS1 */
1356 free((char*)G.PS1);
1357 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1358 prompt_str = G.PS1;
1359 } else
1360 prompt_str = G.PS2;
1361 } else
1362 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001363 debug_printf("result '%s'\n", prompt_str);
1364 return prompt_str;
1365}
1366
1367static void get_user_input(struct in_str *i)
1368{
1369 int r;
1370 const char *prompt_str;
1371
1372 prompt_str = setup_prompt_string(i->promptmode);
1373#if ENABLE_FEATURE_EDITING
1374 /* Enable command line editing only while a command line
1375 * is actually being read */
1376 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001377 G.flag_SIGINT = 0;
1378 /* buglet: SIGINT will not make new prompt to appear _at once_,
1379 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001380 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001381 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001382 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001383 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001384 i->eof_flag = (r < 0);
1385 if (i->eof_flag) { /* EOF/error detected */
1386 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1387 G.user_input_buf[1] = '\0';
1388 }
1389#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001390 do {
1391 G.flag_SIGINT = 0;
1392 fputs(prompt_str, stdout);
1393 fflush(stdout);
1394 G.user_input_buf[0] = r = fgetc(i->file);
1395 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001396//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001397 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001398 i->eof_flag = (r == EOF);
1399#endif
1400 i->p = G.user_input_buf;
1401}
1402
1403#endif /* INTERACTIVE */
1404
1405/* This is the magic location that prints prompts
1406 * and gets data back from the user */
1407static int file_get(struct in_str *i)
1408{
1409 int ch;
1410
1411 /* If there is data waiting, eat it up */
1412 if (i->p && *i->p) {
1413#if ENABLE_HUSH_INTERACTIVE
1414 take_cached:
1415#endif
1416 ch = *i->p++;
1417 if (i->eof_flag && !*i->p)
1418 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001419 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001420 } else {
1421 /* need to double check i->file because we might be doing something
1422 * more complicated by now, like sourcing or substituting. */
1423#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001424 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001425 do {
1426 get_user_input(i);
1427 } while (!*i->p); /* need non-empty line */
1428 i->promptmode = 1; /* PS2 */
1429 i->promptme = 0;
1430 goto take_cached;
1431 }
1432#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001433 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001434 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001435 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001436#if ENABLE_HUSH_INTERACTIVE
1437 if (ch == '\n')
1438 i->promptme = 1;
1439#endif
1440 return ch;
1441}
1442
Denis Vlasenko913a2012009-04-05 22:17:04 +00001443/* All callers guarantee this routine will never
1444 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001445 */
1446static int file_peek(struct in_str *i)
1447{
1448 int ch;
1449 if (i->p && *i->p) {
1450 if (i->eof_flag && !i->p[1])
1451 return EOF;
1452 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001453 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001454 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001455 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001456 i->eof_flag = (ch == EOF);
1457 i->peek_buf[0] = ch;
1458 i->peek_buf[1] = '\0';
1459 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001460 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001461 return ch;
1462}
1463
1464static void setup_file_in_str(struct in_str *i, FILE *f)
1465{
1466 i->peek = file_peek;
1467 i->get = file_get;
1468#if ENABLE_HUSH_INTERACTIVE
1469 i->promptme = 1;
1470 i->promptmode = 0; /* PS1 */
1471#endif
1472 i->file = f;
1473 i->p = NULL;
1474}
1475
1476static void setup_string_in_str(struct in_str *i, const char *s)
1477{
1478 i->peek = static_peek;
1479 i->get = static_get;
1480#if ENABLE_HUSH_INTERACTIVE
1481 i->promptme = 1;
1482 i->promptmode = 0; /* PS1 */
1483#endif
1484 i->p = s;
1485 i->eof_flag = 0;
1486}
1487
1488
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001489/*
1490 * o_string support
1491 */
1492#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001493
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001494static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001495{
1496 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001497 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001498 if (o->data)
1499 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001500}
1501
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001502static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001503{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001504 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001505 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001506}
1507
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001508static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1509{
1510 free(o->data);
1511}
1512
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001513static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001514{
1515 if (o->length + len > o->maxlen) {
1516 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1517 o->data = xrealloc(o->data, 1 + o->maxlen);
1518 }
1519}
1520
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001521static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001522{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001523 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1524 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001525 o->data[o->length] = ch;
1526 o->length++;
1527 o->data[o->length] = '\0';
1528}
1529
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001530static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001531{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001532 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001533 memcpy(&o->data[o->length], str, len);
1534 o->length += len;
1535 o->data[o->length] = '\0';
1536}
1537
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001538#if !BB_MMU
1539static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001540{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001541 o_addblock(o, str, strlen(str));
1542}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001543static void nommu_addchr(o_string *o, int ch)
1544{
1545 if (o)
1546 o_addchr(o, ch);
1547}
1548#else
1549#define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001550#endif
1551
1552static void o_addstr_with_NUL(o_string *o, const char *str)
1553{
1554 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001555}
1556
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001557static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001558{
1559 while (len) {
1560 o_addchr(o, *str);
1561 if (*str++ == '\\'
1562 && (*str != '*' && *str != '?' && *str != '[')
1563 ) {
1564 o_addchr(o, '\\');
1565 }
1566 len--;
1567 }
1568}
1569
Eric Andersen25f27032001-04-26 23:22:31 +00001570/* My analysis of quoting semantics tells me that state information
1571 * is associated with a destination, not a source.
1572 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001573static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001574{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001575 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001576 char *found = strchr("*?[\\", ch);
1577 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001578 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001579 o_grow_by(o, sz);
1580 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001581 o->data[o->length] = '\\';
1582 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001583 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001584 o->data[o->length] = ch;
1585 o->length++;
1586 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001587}
1588
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001589static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001590{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001591 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001592 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001593 sz++;
1594 o->data[o->length] = '\\';
1595 o->length++;
1596 }
1597 o_grow_by(o, sz);
1598 o->data[o->length] = ch;
1599 o->length++;
1600 o->data[o->length] = '\0';
1601}
1602
1603static void o_addQstr(o_string *o, const char *str, int len)
1604{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001605 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001606 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001607 return;
1608 }
1609 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001610 char ch;
1611 int sz;
1612 int ordinary_cnt = strcspn(str, "*?[\\");
1613 if (ordinary_cnt > len) /* paranoia */
1614 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001615 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001616 if (ordinary_cnt == len)
1617 return;
1618 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001619 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001620
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001621 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001622 sz = 1;
1623 if (ch) { /* it is necessarily one of "*?[\\" */
1624 sz++;
1625 o->data[o->length] = '\\';
1626 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001627 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001628 o_grow_by(o, sz);
1629 o->data[o->length] = ch;
1630 o->length++;
1631 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001632 }
1633}
1634
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001635/* A special kind of o_string for $VAR and `cmd` expansion.
1636 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001637 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001638 * list[i] contains an INDEX (int!) into this string data.
1639 * It means that if list[] needs to grow, data needs to be moved higher up
1640 * but list[i]'s need not be modified.
1641 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001642 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001643 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1644 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001645#if DEBUG_EXPAND || DEBUG_GLOB
1646static void debug_print_list(const char *prefix, o_string *o, int n)
1647{
1648 char **list = (char**)o->data;
1649 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1650 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001651
1652 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001653 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1654 prefix, list, n, string_start, o->length, o->maxlen);
1655 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001656 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001657 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1658 o->data + (int)list[i] + string_start,
1659 o->data + (int)list[i] + string_start);
1660 i++;
1661 }
1662 if (n) {
1663 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001664 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001665 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001666 }
1667}
1668#else
1669#define debug_print_list(prefix, o, n) ((void)0)
1670#endif
1671
1672/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1673 * in list[n] so that it points past last stored byte so far.
1674 * It returns n+1. */
1675static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001676{
1677 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001678 int string_start;
1679 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001680
1681 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001682 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1683 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001684 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001685 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001686 /* list[n] points to string_start, make space for 16 more pointers */
1687 o->maxlen += 0x10 * sizeof(list[0]);
1688 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001689 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001690 memmove(list + n + 0x10, list + n, string_len);
1691 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001692 } else {
1693 debug_printf_list("list[%d]=%d string_start=%d\n",
1694 n, string_len, string_start);
1695 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001696 } else {
1697 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001698 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1699 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001700 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1701 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001702 o->has_empty_slot = 0;
1703 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001704 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001705 return n + 1;
1706}
1707
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001708/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001709static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001710{
1711 char **list = (char**)o->data;
1712 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1713
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001714 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001715}
1716
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001717/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001718 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001719static int o_glob(o_string *o, int n)
1720{
1721 glob_t globdata;
1722 int gr;
1723 char *pattern;
1724
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001725 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001726 if (!o->data)
1727 return o_save_ptr_helper(o, n);
1728 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001729 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001730 if (!glob_needed(pattern)) {
1731 literal:
1732 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001733 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001734 return o_save_ptr_helper(o, n);
1735 }
1736
1737 memset(&globdata, 0, sizeof(globdata));
1738 gr = glob(pattern, 0, NULL, &globdata);
1739 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1740 if (gr == GLOB_NOSPACE)
1741 bb_error_msg_and_die("out of memory during glob");
1742 if (gr == GLOB_NOMATCH) {
1743 globfree(&globdata);
1744 goto literal;
1745 }
1746 if (gr != 0) { /* GLOB_ABORTED ? */
1747//TODO: testcase for bad glob pattern behavior
1748 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1749 }
1750 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1751 char **argv = globdata.gl_pathv;
1752 o->length = pattern - o->data; /* "forget" pattern */
1753 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001754 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001755 n = o_save_ptr_helper(o, n);
1756 argv++;
1757 if (!*argv)
1758 break;
1759 }
1760 }
1761 globfree(&globdata);
1762 if (DEBUG_GLOB)
1763 debug_print_list("o_glob returning", o, n);
1764 return n;
1765}
1766
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001767/* If o->o_glob == 1, glob the string so far remembered.
1768 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001769static int o_save_ptr(o_string *o, int n)
1770{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001771 if (o->o_glob) { /* if globbing is requested */
1772 /* If o->has_empty_slot, list[n] was already globbed
1773 * (if it was requested back then when it was filled)
1774 * so don't do that again! */
1775 if (!o->has_empty_slot)
1776 return o_glob(o, n); /* o_save_ptr_helper is inside */
1777 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001778 return o_save_ptr_helper(o, n);
1779}
1780
1781/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001782static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001783{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001784 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001785 int string_start;
1786
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001787 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1788 if (DEBUG_EXPAND)
1789 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001790 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001791 list = (char**)o->data;
1792 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1793 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001794 while (n) {
1795 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001796 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001797 }
1798 return list;
1799}
1800
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001801
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001802/* Expansion can recurse */
1803#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001804static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001805#endif
1806static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001807#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001808#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001809 parse_stream_dquoted(dest, input, dquote_end)
1810#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001811static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001812 o_string *dest,
1813 struct in_str *input,
1814 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001815
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001816/* expand_strvec_to_strvec() takes a list of strings, expands
1817 * all variable references within and returns a pointer to
1818 * a list of expanded strings, possibly with larger number
1819 * of strings. (Think VAR="a b"; echo $VAR).
1820 * This new list is allocated as a single malloc block.
1821 * NULL-terminated list of char* pointers is at the beginning of it,
1822 * followed by strings themself.
1823 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001824
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001825/* Store given string, finalizing the word and starting new one whenever
1826 * we encounter IFS char(s). This is used for expanding variable values.
1827 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1828static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001829{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001830 while (1) {
1831 int word_len = strcspn(str, G.ifs);
1832 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001833 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001834 o_addQstr(output, str, word_len);
1835 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001836 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837 str += word_len;
1838 }
1839 if (!*str) /* EOL - do not finalize word */
1840 break;
1841 o_addchr(output, '\0');
1842 debug_print_list("expand_on_ifs", output, n);
1843 n = o_save_ptr(output, n);
1844 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001845 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001846 debug_print_list("expand_on_ifs[1]", output, n);
1847 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001848}
1849
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001850/* Helper to expand $((...)) and heredoc body. These act as if
1851 * they are in double quotes, with the exception that they are not :).
1852 * Just the rules are similar: "expand only $var and `cmd`"
1853 *
1854 * Returns malloced string.
1855 * As an optimization, we return NULL if expansion is not needed.
1856 */
1857static char *expand_pseudo_dquoted(const char *str)
1858{
1859 char *exp_str;
1860 struct in_str input;
1861 o_string dest = NULL_O_STRING;
1862
1863 if (strchr(str, '$') == NULL
1864#if ENABLE_HUSH_TICK
1865 && strchr(str, '`') == NULL
1866#endif
1867 ) {
1868 return NULL;
1869 }
1870
1871 /* We need to expand. Example:
1872 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1873 */
1874 setup_string_in_str(&input, str);
1875 parse_stream_dquoted(NULL, &dest, &input, EOF);
1876 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1877 exp_str = expand_string_to_string(dest.data);
1878 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1879 o_free_unsafe(&dest);
1880 return exp_str;
1881}
1882
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001883/* Expand all variable references in given string, adding words to list[]
1884 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1885 * to be filled). This routine is extremely tricky: has to deal with
1886 * variables/parameters with whitespace, $* and $@, and constructs like
1887 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1888static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001889{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001890 /* or_mask is either 0 (normal case) or 0x80
1891 * (expansion of right-hand side of assignment == 1-element expand.
1892 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001893
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001894 char first_ch, ored_ch;
1895 int i;
1896 const char *val;
Mike Frysingera4f331d2009-04-07 06:03:22 +00001897 char *dyn_val, *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001898
Mike Frysingera4f331d2009-04-07 06:03:22 +00001899 dyn_val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001900 ored_ch = 0;
1901
1902 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1903 debug_print_list("expand_vars_to_list", output, n);
1904 n = o_save_ptr(output, n);
1905 debug_print_list("expand_vars_to_list[0]", output, n);
1906
1907 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1908#if ENABLE_HUSH_TICK
1909 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001910#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001911#if ENABLE_SH_MATH_SUPPORT
1912 char arith_buf[sizeof(arith_t)*3 + 2];
1913#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001914 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001915 debug_print_list("expand_vars_to_list[1]", output, n);
1916 arg = ++p;
1917 p = strchr(p, SPECIAL_VAR_SYMBOL);
1918
1919 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1920 /* "$@" is special. Even if quoted, it can still
1921 * expand to nothing (not even an empty string) */
1922 if ((first_ch & 0x7f) != '@')
1923 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001924
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001925 val = NULL;
1926 switch (first_ch & 0x7f) {
1927 /* Highest bit in first_ch indicates that var is double-quoted */
1928 case '$': /* pid */
1929 val = utoa(G.root_pid);
1930 break;
1931 case '!': /* bg pid */
1932 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1933 break;
1934 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001935 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001936 break;
1937 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001938 if (arg[1] != SPECIAL_VAR_SYMBOL)
1939 /* actually, it's a ${#var} */
1940 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001941 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1942 break;
1943 case '*':
1944 case '@':
1945 i = 1;
1946 if (!G.global_argv[i])
1947 break;
1948 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1949 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001950 smallint sv = output->o_escape;
1951 /* unquoted var's contents should be globbed, so don't escape */
1952 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001953 while (G.global_argv[i]) {
1954 n = expand_on_ifs(output, n, G.global_argv[i]);
1955 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1956 if (G.global_argv[i++][0] && G.global_argv[i]) {
1957 /* this argv[] is not empty and not last:
1958 * put terminating NUL, start new word */
1959 o_addchr(output, '\0');
1960 debug_print_list("expand_vars_to_list[2]", output, n);
1961 n = o_save_ptr(output, n);
1962 debug_print_list("expand_vars_to_list[3]", output, n);
1963 }
1964 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001965 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001966 } else
1967 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1968 * and in this case should treat it like '$*' - see 'else...' below */
1969 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1970 while (1) {
1971 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1972 if (++i >= G.global_argc)
1973 break;
1974 o_addchr(output, '\0');
1975 debug_print_list("expand_vars_to_list[4]", output, n);
1976 n = o_save_ptr(output, n);
1977 }
1978 } else { /* quoted $*: add as one word */
1979 while (1) {
1980 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1981 if (!G.global_argv[++i])
1982 break;
1983 if (G.ifs[0])
1984 o_addchr(output, G.ifs[0]);
1985 }
1986 }
1987 break;
1988 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1989 /* "Empty variable", used to make "" etc to not disappear */
1990 arg++;
1991 ored_ch = 0x80;
1992 break;
1993#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001994 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001995 *p = '\0';
1996 arg++;
1997//TODO: can we just stuff it into "output" directly?
1998 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001999 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002000 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2001 val = subst_result.data;
2002 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002003#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002004#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002005 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002006 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002007 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002008 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002009 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002010
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002011 arg++; /* skip '+' */
2012 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002013 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002014
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002015 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002016 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002017 hooks.setvar = arith_set_local_var;
2018 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002019 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2020 free(exp_str);
2021
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002022 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002023 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002024 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002025 case -3:
2026 msg = "exponent less than 0";
2027 break;
2028 case -2:
2029 msg = "divide by 0";
2030 break;
2031 case -5:
2032 msg = "expression recursion loop detected";
2033 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002034 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002035 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002036 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002037 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002038 sprintf(arith_buf, arith_t_fmt, res);
2039 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002040 break;
2041 }
2042#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002043 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002044 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002045 bool exp_len = false;
2046 bool exp_null = false;
2047 char *var = arg;
2048 char exp_save = exp_save; /* for compiler */
2049 char exp_op = exp_op; /* for compiler */
2050 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002051 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002052
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002053 *p = '\0';
2054 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002055
2056 /* prepare for expansions */
2057 if (var[0] == '#') {
2058 /* handle length expansion ${#var} */
2059 exp_len = true;
2060 ++var;
2061 } else {
2062 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002063 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002064 if (!var[exp_off])
2065 exp_off = 0;
2066 if (exp_off) {
2067 exp_save = var[exp_off];
2068 exp_null = exp_save == ':';
2069 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002070 if (exp_null)
2071 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002072 exp_op = *exp_word++;
2073 var[exp_off] = '\0';
2074 }
2075 }
2076
2077 /* lookup the variable in question */
2078 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002079 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002080 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002081 if (i < G.global_argc)
2082 val = G.global_argv[i];
2083 /* else val remains NULL: $N with too big N */
2084 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002085 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002086
2087 /* handle any expansions */
2088 if (exp_len) {
2089 debug_printf_expand("expand: length of '%s' = ", val);
2090 val = utoa(val ? strlen(val) : 0);
2091 debug_printf_expand("%s\n", val);
2092 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002093 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002094 if (val) {
2095 /* we need to do a pattern match */
2096 bool zero;
2097 char *loc;
2098 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
2099 if (exp_op == *exp_word) /* ## or %% */
2100 ++exp_word;
2101 val = dyn_val = xstrdup(val);
2102 loc = scan(dyn_val, exp_word, zero);
2103 if (zero)
2104 val = loc;
2105 else
2106 *loc = '\0';
2107 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002108 } else {
2109 /* we need to do an expansion */
2110 int exp_test = (!val || (exp_null && !val[0]));
2111 if (exp_op == '+')
2112 exp_test = !exp_test;
2113 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2114 exp_null ? "true" : "false", exp_test);
2115 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002116 if (exp_op == '?') {
2117//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002118 /* ${var?[error_msg_if_unset]} */
2119 /* ${var:?[error_msg_if_unset_or_null]} */
2120 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002121 die_if_script("%s: %s",
2122 var,
2123 exp_word[0] ? exp_word : "parameter null or not set"
2124 );
2125 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002126 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002127 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002128
Mike Frysingera4f331d2009-04-07 06:03:22 +00002129 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002130 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002131 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002132 /* mimic bash message */
2133 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002134 val = NULL;
2135 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002136 char *new_var = xasprintf("%s=%s", var, val);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002137 set_local_var(new_var, -1, 0);
2138 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002139 }
2140 }
2141 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002142
Mike Frysinger6379bb42009-03-28 18:55:03 +00002143 var[exp_off] = exp_save;
2144 }
2145
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002146 arg[0] = first_ch;
2147#if ENABLE_HUSH_TICK
2148 store_val:
2149#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002151 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002152 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002153 /* unquoted var's contents should be globbed, so don't escape */
2154 smallint sv = output->o_escape;
2155 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002156 n = expand_on_ifs(output, n, val);
2157 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002158 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002159 }
2160 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002161 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002162 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002163 } /* default: */
2164 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002165 if (val) {
2166 o_addQstr(output, val, strlen(val));
2167 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002168 free(dyn_val);
2169 dyn_val = NULL;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002170 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002171 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002172 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002173
2174#if ENABLE_HUSH_TICK
2175 o_free(&subst_result);
2176#endif
2177 arg = ++p;
2178 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2179
2180 if (arg[0]) {
2181 debug_print_list("expand_vars_to_list[a]", output, n);
2182 /* this part is literal, and it was already pre-quoted
2183 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002184 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002185 debug_print_list("expand_vars_to_list[b]", output, n);
2186 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2187 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2188 ) {
2189 n--;
2190 /* allow to reuse list[n] later without re-growth */
2191 output->has_empty_slot = 1;
2192 } else {
2193 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002194 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002195 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002196}
2197
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002199{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002200 int n;
2201 char **list;
2202 char **v;
2203 o_string output = NULL_O_STRING;
2204
2205 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002206 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002207 /* (unquoted $var will temporarily switch it off) */
2208 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002209 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002210
2211 n = 0;
2212 v = argv;
2213 while (*v) {
2214 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2215 v++;
2216 }
2217 debug_print_list("expand_variables", &output, n);
2218
2219 /* output.data (malloced in one block) gets returned in "list" */
2220 list = o_finalize_list(&output, n);
2221 debug_print_strings("expand_variables[1]", list);
2222 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002223}
2224
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002225static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002226{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002227 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002228}
2229
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002230/* Used for expansion of right hand of assignments */
2231/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2232 * "v=/bin/c*" */
2233static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002234{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002235 char *argv[2], **list;
2236
2237 argv[0] = (char*)str;
2238 argv[1] = NULL;
2239 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2240 if (HUSH_DEBUG)
2241 if (!list[0] || list[1])
2242 bb_error_msg_and_die("BUG in varexp2");
2243 /* actually, just move string 2*sizeof(char*) bytes back */
2244 overlapping_strcpy((char*)list, list[0]);
2245 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2246 return (char*)list;
2247}
2248
2249/* Used for "eval" builtin */
2250static char* expand_strvec_to_string(char **argv)
2251{
2252 char **list;
2253
2254 list = expand_variables(argv, 0x80);
2255 /* Convert all NULs to spaces */
2256 if (list[0]) {
2257 int n = 1;
2258 while (list[n]) {
2259 if (HUSH_DEBUG)
2260 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2261 bb_error_msg_and_die("BUG in varexp3");
2262 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2263 n++;
2264 }
2265 }
2266 overlapping_strcpy((char*)list, list[0]);
2267 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2268 return (char*)list;
2269}
2270
2271static char **expand_assignments(char **argv, int count)
2272{
2273 int i;
2274 char **p = NULL;
2275 /* Expand assignments into one string each */
2276 for (i = 0; i < count; i++) {
2277 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2278 }
2279 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002280}
2281
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002282
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002283#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002284/* never called */
2285void re_execute_shell(const char *s, char *argv0, char **argv);
2286
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002287#define clean_up_after_re_execute() ((void)0)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002288
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002289static void reset_traps_to_defaults(void)
2290{
2291 unsigned sig;
2292 int dirty;
2293
2294 if (!G.traps)
2295 return;
2296 dirty = 0;
2297 for (sig = 0; sig < NSIG; sig++) {
2298 if (!G.traps[sig])
2299 continue;
2300 free(G.traps[sig]);
2301 G.traps[sig] = NULL;
2302 /* There is no signal for 0 (EXIT) */
2303 if (sig == 0)
2304 continue;
2305 /* there was a trap handler, we are removing it
2306 * (if sig has non-DFL handling,
2307 * we don't need to do anything) */
2308 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2309 continue;
2310 sigdelset(&G.blocked_set, sig);
2311 dirty = 1;
2312 }
2313 if (dirty)
2314 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2315}
2316
2317#else /* !BB_MMU */
2318
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002319static void re_execute_shell(const char *s, char *g_argv0, char **g_argv) NORETURN;
2320static void re_execute_shell(const char *s, char *g_argv0, char **g_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002321{
2322 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002323 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002324 struct variable *cur;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002325#if ENABLE_HUSH_FUNCTIONS
2326 struct function *funcp;
2327#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002328 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002329 unsigned cnt;
2330
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002331 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002332 argv = heredoc_argv;
2333 argv[0] = (char *) G.argv0_for_re_execing;
2334 argv[1] = (char *) "-<";
2335 argv[2] = (char *) s;
2336 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002337 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002338 goto do_exec;
2339 }
2340
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002341 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2342 , (unsigned) G.root_pid
2343 , (unsigned) G.last_bg_pid
2344 , (unsigned) G.last_exitcode
2345 USE_HUSH_LOOPS(, G.depth_of_loop)
2346 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002347 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002348 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002349 */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002350 cnt = 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002351 for (cur = G.top_var; cur; cur = cur->next) {
2352 if (!cur->flg_export || cur->flg_read_only)
2353 cnt += 2;
2354 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002355#if ENABLE_HUSH_FUNCTIONS
2356 for (funcp = G.top_func; funcp; funcp = funcp->next)
2357 cnt += 3;
2358#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002359 pp = g_argv;
2360 while (*pp++)
2361 cnt++;
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002362 G.argv_from_re_execing = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002363 *pp++ = (char *) G.argv0_for_re_execing;
2364 *pp++ = param_buf;
2365 for (cur = G.top_var; cur; cur = cur->next) {
2366 if (cur->varstr == hush_version_str)
2367 continue;
2368 if (cur->flg_read_only) {
2369 *pp++ = (char *) "-R";
2370 *pp++ = cur->varstr;
2371 } else if (!cur->flg_export) {
2372 *pp++ = (char *) "-V";
2373 *pp++ = cur->varstr;
2374 }
2375 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002376#if ENABLE_HUSH_FUNCTIONS
2377 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2378 *pp++ = (char *) "-F";
2379 *pp++ = funcp->name;
2380 *pp++ = funcp->body_as_string;
2381 }
2382#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002383 /* We can pass activated traps here. Say, -Tnn:trap_string
2384 *
2385 * However, POSIX says that subshells reset signals with traps
2386 * to SIG_DFL.
2387 * I tested bash-3.2 and it not only does that with true subshells
2388 * of the form ( list ), but with any forked children shells.
2389 * I set trap "echo W" WINCH; and then tried:
2390 *
2391 * { echo 1; sleep 20; echo 2; } &
2392 * while true; do echo 1; sleep 20; echo 2; break; done &
2393 * true | { echo 1; sleep 20; echo 2; } | cat
2394 *
2395 * In all these cases sending SIGWINCH to the child shell
2396 * did not run the trap. If I add trap "echo V" WINCH;
2397 * _inside_ group (just before echo 1), it works.
2398 *
2399 * I conclude it means we don't need to pass active traps here.
2400 * exec syscall below resets them to SIG_DFL for us.
2401 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002402 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002403 *pp++ = (char *) s;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002404 *pp++ = g_argv0;
2405 while (*g_argv)
2406 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002407 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002408 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002409
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002410 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002411 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2412 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002413 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002414 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002415 if (argv[0][0] == '/')
2416 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002417 xfunc_error_retval = 127;
2418 bb_error_msg_and_die("can't re-execute the shell");
2419}
2420
2421static void clean_up_after_re_execute(void)
2422{
2423 char **pp = G.argv_from_re_execing;
2424 if (pp) {
2425 /* Must match re_execute_shell's allocations (if any) */
2426 free(pp);
2427 G.argv_from_re_execing = NULL;
2428 }
2429}
2430#endif /* !BB_MMU */
2431
2432
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002433static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002434{
2435 struct fd_pair pair;
2436 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002437 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002438 /* the _body_ of heredoc (misleading field name) */
2439 const char *heredoc = redir->rd_filename;
2440 char *expanded;
2441
2442 expanded = NULL;
2443 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2444 expanded = expand_pseudo_dquoted(heredoc);
2445 if (expanded)
2446 heredoc = expanded;
2447 }
2448 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002449
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002450 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002451 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002452 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002453
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002454 /* Try writing without forking. Newer kernels have
2455 * dynamically growing pipes. Must use non-blocking write! */
2456 ndelay_on(pair.wr);
2457 while (1) {
2458 written = write(pair.wr, heredoc, len);
2459 if (written <= 0)
2460 break;
2461 len -= written;
2462 if (len == 0) {
2463 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002464 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002465 return;
2466 }
2467 heredoc += written;
2468 }
2469 ndelay_off(pair.wr);
2470
2471 /* Okay, pipe buffer was not big enough */
2472 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002473 * for the unsuspecting parent process. Child creates a grandchild
2474 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002475 * (that exec happens after we return from this function) */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002476 pid = vfork();
2477 if (pid < 0)
2478 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002479 if (pid == 0) {
2480 /* child */
2481 pid = BB_MMU ? fork() : vfork();
2482 if (pid < 0)
2483 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2484 if (pid != 0)
2485 _exit(0);
2486 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002487 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002488#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002489 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002490 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002491#else
2492 /* Delegate blocking writes to another process */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002493 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002494 xmove_fd(pair.wr, STDOUT_FILENO);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002495 re_execute_shell(heredoc, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002496#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002497 }
2498 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002499 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002500 clean_up_after_re_execute();
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002501 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002502 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002503 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002504}
2505
Eric Andersen25f27032001-04-26 23:22:31 +00002506/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2507 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002508static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002509{
2510 int openfd, mode;
2511 struct redir_struct *redir;
2512
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002513 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002514 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002515 /* rd_fd<<HERE case */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002516 if (squirrel && redir->rd_fd < 3) {
2517 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002518 }
2519 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2520 * of the heredoc */
2521 debug_printf_parse("set heredoc '%s'\n",
2522 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002523 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002524 continue;
2525 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002526
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002527 if (redir->rd_dup == REDIRFD_TO_FILE) {
2528 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002529 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002530 if (redir->rd_filename == NULL) {
2531 /* Something went wrong in the parse.
2532 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002533 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002534 continue;
2535 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002536 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002537 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002538 openfd = open_or_warn(p, mode);
2539 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002540 if (openfd < 0) {
2541 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002542 * bash and ash both lose it as well (though zsh doesn't!) */
2543//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002544 return 1;
2545 }
2546 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002547 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002548 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002549 }
2550
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002551 if (openfd != redir->rd_fd) {
2552 if (squirrel && redir->rd_fd < 3) {
2553 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002554 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002555 if (openfd == REDIRFD_CLOSE) {
2556 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002557 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002558 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002559 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002560 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002561 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002562 }
Eric Andersen25f27032001-04-26 23:22:31 +00002563 }
2564 }
2565 return 0;
2566}
2567
2568static void restore_redirects(int squirrel[])
2569{
2570 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002571 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002572 fd = squirrel[i];
2573 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002574 /* We simply die on error */
2575 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002576 }
2577 }
2578}
2579
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002581static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002582
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002583/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002584static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002585{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002586 char **p;
2587 struct command *command;
2588 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002589 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002590
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002591 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002592 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002593 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002594 for (i = 0; i < pi->num_cmds; i++) {
2595 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002596 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002597 if (command->argv) {
2598 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002599 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002600 }
2601 free_strings(command->argv);
2602 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002603 }
2604 /* not "else if": on syntax error, we may have both! */
2605 if (command->group) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002606 debug_printf_clean(" begin group (grp_type:%d)\n",
2607 command->grp_type);
2608 free_pipe_list(command->group);
2609 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002610 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002611 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002612 /* else is crucial here.
2613 * If group != NULL, child_func is meaningless */
2614#if ENABLE_HUSH_FUNCTIONS
2615 else if (command->child_func) {
2616 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2617 command->child_func->parent_cmd = NULL;
2618 }
2619#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002620#if !BB_MMU
2621 free(command->group_as_string);
2622 command->group_as_string = NULL;
2623#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002624 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002625 debug_printf_clean(" redirect %d%s",
2626 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002627 /* guard against the case >$FOO, where foo is unset or blank */
2628 if (r->rd_filename) {
2629 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2630 free(r->rd_filename);
2631 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002633 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002634 rnext = r->next;
2635 free(r);
2636 }
2637 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002638 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002639 free(pi->cmds); /* children are an array, they get freed all at once */
2640 pi->cmds = NULL;
2641#if ENABLE_HUSH_JOB
2642 free(pi->cmdtext);
2643 pi->cmdtext = NULL;
2644#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002645}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002646
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002647static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002648{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002649 struct pipe *pi, *next;
2650
2651 for (pi = head; pi; pi = next) {
2652#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002653 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002654#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002655 free_pipe(pi);
2656 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002657 next = pi->next;
2658 /*pi->next = NULL;*/
2659 free(pi);
2660 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002661}
2662
2663
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002664static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002665#if BB_MMU
2666#define parse_stream(pstring, input, end_trigger) \
2667 parse_stream(input, end_trigger)
2668#endif
2669static struct pipe *parse_stream(char **pstring,
2670 struct in_str *input,
2671 int end_trigger);
2672static void parse_and_run_string(const char *s);
2673
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002674
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002675static const struct built_in_command* find_builtin(const char *name)
2676{
2677 const struct built_in_command *x;
2678 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2679 if (strcmp(name, x->cmd) != 0)
2680 continue;
2681 debug_printf_exec("found builtin '%s'\n", name);
2682 return x;
2683 }
2684 return NULL;
2685}
2686
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002687#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002688static const struct function *find_function(const char *name)
2689{
2690 const struct function *funcp = G.top_func;
2691 while (funcp) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002692 if (strcmp(name, funcp->name) == 0) {
2693 break;
2694 }
2695 funcp = funcp->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002696 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002697 debug_printf_exec("found function '%s'\n", name);
2698 return funcp;
2699}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002700
Denis Vlasenkobc569742009-04-12 20:35:19 +00002701/* Note: takes ownership on name ptr */
2702static struct function *new_function(char *name)
2703{
2704 struct function *funcp;
2705 struct function **funcpp = &G.top_func;
2706
2707 while ((funcp = *funcpp) != NULL) {
2708 struct command *cmd;
2709
2710 if (strcmp(funcp->name, name) != 0) {
2711 funcpp = &funcp->next;
2712 continue;
2713 }
2714
2715 cmd = funcp->parent_cmd;
2716 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2717 if (!cmd) {
2718 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2719 free(funcp->name);
2720 /* Note: if !funcp->body, do not free body_as_string!
2721 * This is a special case of "-F name body" function:
2722 * body_as_string was not malloced! */
2723 if (funcp->body) {
2724 free_pipe_list(funcp->body);
2725#if !BB_MMU
2726 free(funcp->body_as_string);
2727#endif
2728 }
2729 } else {
2730 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2731 cmd->argv[0] = funcp->name;
2732 cmd->group = funcp->body;
2733#if !BB_MMU
2734 cmd->group_as_string = funcp->body_as_string;
2735#endif
2736 }
2737 goto skip;
2738 }
2739 debug_printf_exec("remembering new function '%s'\n", command->argv[0]);
2740 funcp = *funcpp = xzalloc(sizeof(*funcp));
2741 /*funcp->next = NULL;*/
2742 skip:
2743 funcp->name = name;
2744 return funcp;
2745}
2746
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002747static void exec_function(const struct function *funcp, char **argv) NORETURN;
2748static void exec_function(const struct function *funcp, char **argv)
2749{
2750# if BB_MMU
2751 int n = 1;
2752
2753 argv[0] = G.global_argv[0];
2754 G.global_argv = argv;
2755 while (*++argv)
2756 n++;
2757 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002758 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002759 n = run_list(funcp->body);
2760 fflush(NULL);
2761 _exit(n);
2762# else
2763 re_execute_shell(funcp->body_as_string, G.global_argv[0], argv + 1);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002764# endif
2765}
2766
2767static int run_function(const struct function *funcp, char **argv)
2768{
2769 int n;
2770 char **pp;
2771 char *sv_argv0;
2772 smallint sv_g_malloced;
2773 int sv_g_argc;
2774 char **sv_g_argv;
2775
2776 sv_argv0 = argv[0];
2777 sv_g_malloced = G.global_args_malloced;
2778 sv_g_argc = G.global_argc;
2779 sv_g_argv = G.global_argv;
2780
2781 pp = argv;
2782 n = 1;
2783 while (*++pp)
2784 n++;
2785
2786 argv[0] = G.global_argv[0]; /* retain $0 */
2787 G.global_args_malloced = 0;
2788 G.global_argc = n;
2789 G.global_argv = argv;
2790
Denis Vlasenkobc569742009-04-12 20:35:19 +00002791 /* On MMU, funcp->body is always non-NULL */
2792#if !BB_MMU
2793 if (!funcp->body) {
2794 /* Function defined by -F */
2795 parse_and_run_string(funcp->body_as_string);
2796 n = G.last_exitcode;
2797 } else
2798#endif
2799 {
2800 n = run_list(funcp->body);
2801 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002802
2803 if (G.global_args_malloced) {
2804 /* function ran "set -- arg1 arg2 ..." */
2805 pp = G.global_argv;
2806 while (*++pp)
2807 free(*pp);
2808 free(G.global_argv);
2809 }
2810
2811 argv[0] = sv_argv0;
2812 G.global_args_malloced = sv_g_malloced;
2813 G.global_argc = sv_g_argc;
2814 G.global_argv = sv_g_argv;
2815
2816 return n;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002817}
2818#endif
2819
2820
Denis Vlasenkocc90f442009-04-08 16:40:34 +00002821#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002822#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2823 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2824#define pseudo_exec(nommu_save, command, argv_expanded) \
2825 pseudo_exec(command, argv_expanded)
2826#endif
2827
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002828/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00002829 * Never returns.
2830 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00002831 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002832 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002833static void pseudo_exec_argv(nommu_save_t *nommu_save,
2834 char **argv, int assignment_cnt,
2835 char **argv_expanded) NORETURN;
2836static void pseudo_exec_argv(nommu_save_t *nommu_save,
2837 char **argv, int assignment_cnt,
2838 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00002839{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002840 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002841
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002842 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002843 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002844 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002845
Denis Vlasenko9504e442008-10-29 01:19:15 +00002846 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002847#if BB_MMU
2848 putenv_all(new_env);
2849 free(new_env); /* optional */
2850#else
2851 nommu_save->new_env = new_env;
2852 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002853#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002854 if (argv_expanded) {
2855 argv = argv_expanded;
2856 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00002857 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002858#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002859 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002860#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002861 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002862
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002863#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
2864 if (strchr(argv[0], '/') != NULL)
2865 goto skip;
2866#endif
2867
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002868 /* On NOMMU, we must never block!
2869 * Example: { sleep 99999 | read line } & echo Ok
2870 * read builtin will block on read syscall, leaving parent blocked
2871 * in vfork. Therefore we can't do this:
2872 */
2873#if BB_MMU
2874 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00002875 * Depending on context, this might be redundant. But it's
2876 * easier to waste a few CPU cycles than it is to figure out
2877 * if this is one of those cases.
2878 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002879 {
2880 int rcode;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002881 const struct built_in_command *x = find_builtin(argv[0]);
2882 if (x) {
2883 rcode = x->function(argv);
2884 fflush(NULL);
2885 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00002886 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002887 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002888#endif
2889#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002890 /* Check if the command matches any functions */
2891 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002892 const struct function *funcp = find_function(argv[0]);
2893 if (funcp) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002894 exec_function(funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002895 }
2896 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002897#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00002898
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002899#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002900 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002901 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002902 int a = find_applet_by_name(argv[0]);
2903 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002904# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002905 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002906 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002907 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002908 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002909# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002910 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002911 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002912 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2913 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002914 /* If they called chroot or otherwise made the binary no longer
2915 * executable, fall through */
2916 }
2917 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002918#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002919
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002920#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002921 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002922#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002923 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002924 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002925 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002926 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002927 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002928}
2929
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002930/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00002931 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002932static void pseudo_exec(nommu_save_t *nommu_save,
2933 struct command *command,
2934 char **argv_expanded) NORETURN;
2935static void pseudo_exec(nommu_save_t *nommu_save,
2936 struct command *command,
2937 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002938{
Denis Vlasenko552433b2009-04-04 19:29:21 +00002939 if (command->argv) {
2940 pseudo_exec_argv(nommu_save, command->argv,
2941 command->assignment_cnt, argv_expanded);
2942 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002943
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002944 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00002945 /* Cases when we are here:
2946 * ( list )
2947 * { list } &
2948 * ... | ( list ) | ...
2949 * ... | { list } | ...
2950 */
2951#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002952 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002953 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002954 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002955 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002956 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002957 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002958 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002959#else
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002960 re_execute_shell(command->group_as_string,
2961 G.global_argv[0],
2962 G.global_argv + 1);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002963#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002964 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002965
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002966 /* Case when we are here: ... | >file */
2967 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002968 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002969}
2970
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002971#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002972static const char *get_cmdtext(struct pipe *pi)
2973{
2974 char **argv;
2975 char *p;
2976 int len;
2977
2978 /* This is subtle. ->cmdtext is created only on first backgrounding.
2979 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002980 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002981 if (pi->cmdtext)
2982 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002983 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002984 if (!argv || !argv[0]) {
2985 pi->cmdtext = xzalloc(1);
2986 return pi->cmdtext;
2987 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002988
2989 len = 0;
2990 do len += strlen(*argv) + 1; while (*++argv);
2991 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002992 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002993 do {
2994 len = strlen(*argv);
2995 memcpy(p, *argv, len);
2996 p += len;
2997 *p++ = ' ';
2998 } while (*++argv);
2999 p[-1] = '\0';
3000 return pi->cmdtext;
3001}
3002
Eric Andersenbafd94f2001-05-02 16:11:59 +00003003static void insert_bg_job(struct pipe *pi)
3004{
3005 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003006 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003007
3008 /* Linear search for the ID of the job to use */
3009 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003010 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003011 if (thejob->jobid >= pi->jobid)
3012 pi->jobid = thejob->jobid + 1;
3013
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003014 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003015 if (!G.job_list) {
3016 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003017 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003018 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003019 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003020 thejob->next = xmalloc(sizeof(*thejob));
3021 thejob = thejob->next;
3022 }
3023
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003024 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00003025 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003026 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3027 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
3028 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003029// TODO: do we really need to have so many fields which are just dead weight
3030// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003031 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003032 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003033 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003034 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003035 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003036
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003037 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00003038 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003039 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003040 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003041 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003042 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003043}
3044
Eric Andersenbafd94f2001-05-02 16:11:59 +00003045static void remove_bg_job(struct pipe *pi)
3046{
3047 struct pipe *prev_pipe;
3048
Denis Vlasenko87a86552008-07-29 19:43:10 +00003049 if (pi == G.job_list) {
3050 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003051 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003052 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003053 while (prev_pipe->next != pi)
3054 prev_pipe = prev_pipe->next;
3055 prev_pipe->next = pi->next;
3056 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003057 if (G.job_list)
3058 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003059 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003060 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003061}
Eric Andersen028b65b2001-06-28 01:10:11 +00003062
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003063/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003064static void delete_finished_bg_job(struct pipe *pi)
3065{
3066 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003067 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003068 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003069 free(pi);
3070}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003071#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003072
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003073/* Check to see if any processes have exited -- if they
3074 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003075static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003076{
Eric Andersenc798b072001-06-22 06:23:03 +00003077 int attributes;
3078 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003079#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003080 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003081#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003082 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003083 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003084
Denis Vlasenkod5762932009-03-31 11:22:57 +00003085 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3086
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003087 errno = 0;
3088// if (G.handled_SIGCHLD == G.count_SIGCHLD)
3089// /* avoid doing syscall, nothing there anyway */
3090// return rcode;
3091
Eric Andersenc798b072001-06-22 06:23:03 +00003092 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003093 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003094 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003095
Denis Vlasenko1359da62007-04-21 23:27:30 +00003096/* Do we do this right?
3097 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003098 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003099 * [3]+ Stopped sleep 20 | false
3100 * bash-3.00# echo $?
3101 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3102 */
3103
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003104//FIXME: non-interactive bash does not continue even if all processes in fg pipe
3105//are stopped. Testcase: "cat | cat" in a script (not on command line)
3106// + killall -STOP cat
3107
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003108 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003109 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003110 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003111 int dead;
3112
3113// i = G.count_SIGCHLD;
3114 childpid = waitpid(-1, &status, attributes);
3115 if (childpid <= 0) {
3116 if (childpid && errno != ECHILD)
3117 bb_perror_msg("waitpid");
3118// else /* Until next SIGCHLD, waitpid's are useless */
3119// G.handled_SIGCHLD = i;
3120 break;
3121 }
3122 dead = WIFEXITED(status) || WIFSIGNALED(status);
3123
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003124#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003125 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003126 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003127 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3128 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003129 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003130 childpid, WTERMSIG(status), WEXITSTATUS(status));
3131 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003132 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003133 childpid, WEXITSTATUS(status));
3134#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003135 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003136 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003137 for (i = 0; i < fg_pipe->num_cmds; i++) {
3138 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3139 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003140 continue;
3141 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
3142 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003143 fg_pipe->cmds[i].pid = 0;
3144 fg_pipe->alive_cmds--;
3145 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003146 /* last process gives overall exitstatus */
3147 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003148 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003149 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003150 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003151 fg_pipe->cmds[i].is_stopped = 1;
3152 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003153 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003154 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3155 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3156 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003157 /* All processes in fg pipe have exited/stopped */
3158#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003159 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003160 insert_bg_job(fg_pipe);
3161#endif
3162 return rcode;
3163 }
3164 /* There are still running processes in the fg pipe */
3165 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003166 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003167 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003168 }
3169
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003170#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003171 /* We asked to wait for bg or orphaned children */
3172 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003173 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003174 for (i = 0; i < pi->num_cmds; i++) {
3175 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003176 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003177 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003178 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003179 /* Happens when shell is used as init process (init=/bin/sh) */
3180 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003181 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003182
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003183 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003184 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003185 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003186 pi->cmds[i].pid = 0;
3187 pi->alive_cmds--;
3188 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003189 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003190 printf(JOB_STATUS_FORMAT, pi->jobid,
3191 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003192 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003193 }
3194 } else {
3195 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003196 pi->cmds[i].is_stopped = 1;
3197 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003198 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003199#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003200 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003201
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003202 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003203}
3204
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003205#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003206static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3207{
3208 pid_t p;
3209 int rcode = checkjobs(fg_pipe);
3210 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00003211 p = getpgid(0); /* pgid of our process */
3212 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003213 tcsetpgrp(G_interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00003214 return rcode;
3215}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003216#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003217
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003218/* Start all the jobs, but don't wait for anything to finish.
3219 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003220 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003221 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003222 * to finish to determine the exit status of the pipe. If the pipe
3223 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003224 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003225 * return value.
3226 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003227 * Returns -1 only if started some children. IOW: we have to
3228 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003229 *
3230 * The only case when we do not need to [v]fork is when the pipe
3231 * is single, non-backgrounded, non-subshell command. Examples:
3232 * cmd ; ... { list } ; ...
3233 * cmd && ... { list } && ...
3234 * cmd || ... { list } || ...
3235 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3236 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003237 * with run_list(). If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003238 *
3239 * Cases when we must fork:
3240 * non-single: cmd | cmd
3241 * backgrounded: cmd & { list } &
3242 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003243 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003244static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003245{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003246 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003247 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003248 int nextin;
3249 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003250 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003251 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003252 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003253 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003254 /* it is not always needed, but we aim to smaller code */
3255 int squirrel[] = { -1, -1, -1 };
3256 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003257
Denis Vlasenko552433b2009-04-04 19:29:21 +00003258 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003259 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003260
Denis Vlasenko552433b2009-04-04 19:29:21 +00003261 USE_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003262 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003263 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003264 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003265
Denis Vlasenko552433b2009-04-04 19:29:21 +00003266 if (pi->num_cmds != 1
3267 || pi->followup == PIPE_BG
3268 || command->grp_type == GRP_SUBSHELL
3269 ) {
3270 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003271 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003272
Denis Vlasenko552433b2009-04-04 19:29:21 +00003273 pi->alive_cmds = 1;
3274
3275 debug_printf_exec(": group:%p argv:'%s'\n",
3276 command->group, command->argv ? command->argv[0] : "NONE");
3277
3278 if (command->group) {
3279#if ENABLE_HUSH_FUNCTIONS
3280 if (command->grp_type == GRP_FUNCTION) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003281 /* "executing" func () { list } */
3282 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003283
Denis Vlasenkobc569742009-04-12 20:35:19 +00003284 funcp = new_function(command->argv[0]);
3285 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003286 funcp->body = command->group;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003287#if !BB_MMU
3288 funcp->body_as_string = command->group_as_string;
3289 command->group_as_string = NULL;
3290#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003291 command->group = NULL;
3292 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003293 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3294 funcp->parent_cmd = command;
3295 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003296
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003297 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3298 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003299 return EXIT_SUCCESS;
3300 }
3301#endif
3302 /* { list } */
3303 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003304 rcode = 1; /* exitcode if redir failed */
3305 if (setup_redirects(command, squirrel) == 0) {
3306 debug_printf_exec(": run_list\n");
3307 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003308 }
Eric Andersen04407e52001-06-07 16:42:05 +00003309 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003310 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003311 debug_leave();
3312 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003313 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003314 }
3315
Denis Vlasenko552433b2009-04-04 19:29:21 +00003316 argv = command->argv ? command->argv : (char **) &null_ptr;
3317 {
3318 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003319#if ENABLE_HUSH_FUNCTIONS
3320 const struct function *funcp;
3321#else
3322 enum { funcp = 0 };
3323#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003324 char **new_env = NULL;
3325 char **old_env = NULL;
3326
Denis Vlasenko552433b2009-04-04 19:29:21 +00003327 if (argv[command->assignment_cnt] == NULL) {
3328 /* Assignments, but no command */
3329 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003330 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003331 restore_redirects(squirrel);
3332 /* Set shell variables */
3333 while (*argv) {
3334 p = expand_string_to_string(*argv);
3335 debug_printf_exec("set shell var:'%s'->'%s'\n",
3336 *argv, p);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003337 set_local_var(p, 0, 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003338 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003339 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003340 /* Do we need to flag set_local_var() errors?
3341 * "assignment to readonly var" and "putenv error"
3342 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003343 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003344 debug_leave();
3345 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003346 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003347 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003348
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003349 /* Expand the rest into (possibly) many strings each */
Denis Vlasenko552433b2009-04-04 19:29:21 +00003350 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003351
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003352 x = find_builtin(argv_expanded[0]);
3353#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003354 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003355 if (!x)
3356 funcp = find_function(argv_expanded[0]);
3357#endif
3358 if (x || funcp) {
3359 if (!funcp) {
3360 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3361 debug_printf("exec with redirects only\n");
3362 rcode = setup_redirects(command, NULL);
3363 goto clean_up_and_ret1;
3364 }
Eric Andersen25f27032001-04-26 23:22:31 +00003365 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003366 /* XXX setup_redirects acts on file descriptors, not FILEs.
3367 * This is perfect for work that comes after exec().
3368 * Is it really safe for inline use? Experimentally,
3369 * things seem to work with glibc. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003370 rcode = setup_redirects(command, squirrel);
3371 if (rcode == 0) {
3372 new_env = expand_assignments(argv, command->assignment_cnt);
3373 old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003374 if (!funcp) {
3375 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003376 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003377 rcode = x->function(argv_expanded) & 0xff;
3378 }
3379#if ENABLE_HUSH_FUNCTIONS
3380 else {
3381 debug_printf_exec(": function '%s' '%s'...\n",
3382 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003383 rcode = run_function(funcp, argv_expanded) & 0xff;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003384 }
3385#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003386 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003387#if ENABLE_FEATURE_SH_STANDALONE
3388 clean_up_and_ret:
3389#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003390 restore_redirects(squirrel);
3391 free_strings_and_unsetenv(new_env, 1);
3392 putenv_all(old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003393 /* Free the pointers, but the strings themselves
3394 * are in environ now, don't use free_strings! */
3395 free(old_env);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003396 clean_up_and_ret1:
3397 free(argv_expanded);
3398 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003399 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003400 debug_printf_exec("run_pipe return %d\n", rcode);
3401 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003402 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003403
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003404#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003405 i = find_applet_by_name(argv_expanded[0]);
3406 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003407 rcode = setup_redirects(command, squirrel);
3408 if (rcode == 0) {
3409 save_nofork_data(&G.nofork_save);
3410 new_env = expand_assignments(argv, command->assignment_cnt);
3411 old_env = putenv_all_and_save_old(new_env);
3412 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003413 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003414 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
3415 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003416 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003417 }
3418#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003419 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003420 }
3421
Denis Vlasenko552433b2009-04-04 19:29:21 +00003422 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003423 /* NB: argv_expanded may already be created, and that
3424 * might include `cmd` runs! Do not rerun it! We *must*
3425 * use argv_expanded if it's non-NULL */
3426
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003427 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003428 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003429 nextin = 0;
3430
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003431 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00003432#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003433 volatile nommu_save_t nommu_save;
3434 nommu_save.new_env = NULL;
3435 nommu_save.old_env = NULL;
3436 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003437#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003438 command = &(pi->cmds[i]);
3439 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003440 debug_printf_exec(": pipe member '%s' '%s'...\n",
3441 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003442 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003443 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003444 }
Eric Andersen25f27032001-04-26 23:22:31 +00003445
3446 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003447 pipefds[0] = 0;
3448 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003449 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003450 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003451
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003452 command->pid = BB_MMU ? fork() : vfork();
3453 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003454#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003455 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003456
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003457 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003458 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003459 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003460 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003461 pgrp = pi->pgrp;
3462 if (pgrp < 0) /* true for 1st process only */
3463 pgrp = getpid();
3464 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003465 /* We do it in *every* child, not just first,
3466 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003467 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003468 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003469 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003470#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00003471 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003472 xmove_fd(pipefds[1], 1); /* write end */
3473 if (pipefds[0] > 1)
3474 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00003475 /* Like bash, explicit redirects override pipes,
3476 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003477 if (setup_redirects(command, NULL))
3478 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00003479
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003480 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003481 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3482
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003483 /* Stores to nommu_save list of env vars putenv'ed
3484 * (NOMMU, on MMU we don't need that) */
3485 /* cast away volatility... */
3486 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003487 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00003488 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003489
Denis Vlasenkof9375282009-04-05 19:13:39 +00003490 /* parent or error */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003491 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003492#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003493 /* Clean up after vforked child */
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003494 clean_up_after_re_execute();
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003495 free(nommu_save.argv);
3496 free_strings_and_unsetenv(nommu_save.new_env, 1);
3497 putenv_all(nommu_save.old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003498 /* Free the pointers, but the strings themselves
3499 * are in environ now, don't use free_strings! */
3500 free(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003501#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003502 free(argv_expanded);
3503 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003504 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003505 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003506 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003507 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003508 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003509#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003510 /* Second and next children need to know pid of first one */
3511 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003512 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003513#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003514 }
Eric Andersen25f27032001-04-26 23:22:31 +00003515
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003516 if (i)
3517 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003518 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003519 close(pipefds[1]); /* write end */
3520 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00003521 nextin = pipefds[0];
3522 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003523
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003524 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003525 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00003526 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3527 return 1;
3528 }
3529
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003530 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003531 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003532 return -1;
3533}
3534
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003535#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003536static void debug_print_tree(struct pipe *pi, int lvl)
3537{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003538 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003539 [PIPE_SEQ] = "SEQ",
3540 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003541 [PIPE_OR ] = "OR" ,
3542 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003543 };
3544 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003545 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003546#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003547 [RES_IF ] = "IF" ,
3548 [RES_THEN ] = "THEN" ,
3549 [RES_ELIF ] = "ELIF" ,
3550 [RES_ELSE ] = "ELSE" ,
3551 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003552#endif
3553#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003554 [RES_FOR ] = "FOR" ,
3555 [RES_WHILE] = "WHILE",
3556 [RES_UNTIL] = "UNTIL",
3557 [RES_DO ] = "DO" ,
3558 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003559#endif
3560#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003561 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003562#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003563#if ENABLE_HUSH_CASE
3564 [RES_CASE ] = "CASE" ,
3565 [RES_MATCH] = "MATCH",
3566 [RES_CASEI] = "CASEI",
3567 [RES_ESAC ] = "ESAC" ,
3568#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00003569 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003570 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003571 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003572 static const char *const GRPTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003573 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00003574 "()",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003575#if ENABLE_HUSH_FUNCTIONS
3576 "func()",
3577#endif
3578 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003579
3580 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003581
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003582 pin = 0;
3583 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003584 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3585 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003586 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003587 while (prn < pi->num_cmds) {
3588 struct command *command = &pi->cmds[prn];
3589 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003590
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003591 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003592 lvl*2, "", prn,
3593 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003594 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003595 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003596 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003597 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003598 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003599 prn++;
3600 continue;
3601 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003602 if (argv) while (*argv) {
3603 fprintf(stderr, " '%s'", *argv);
3604 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003605 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003606 fprintf(stderr, "\n");
3607 prn++;
3608 }
3609 pi = pi->next;
3610 pin++;
3611 }
3612}
3613#endif
3614
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003615/* NB: called by pseudo_exec, and therefore must not modify any
3616 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003617static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003618{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003619#if ENABLE_HUSH_CASE
3620 char *case_word = NULL;
3621#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003622#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003623 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003624 char *for_varname = NULL;
3625 char **for_lcur = NULL;
3626 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00003627#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003628 smallint last_followup;
3629 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003630#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003631 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003632#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003633 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003634#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00003635#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003636 smallint rword; /* enum reserved_style */
3637 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003638#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003639
Denis Vlasenko87a86552008-07-29 19:43:10 +00003640 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003641 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003642
Denis Vlasenko06810332007-05-21 23:30:54 +00003643#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003644 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003645 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3646 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003647 continue;
3648 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003649 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003650 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003651 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003652 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003653 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003654 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003655 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003656 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003657 continue;
3658 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003659 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3660 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003661 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003662 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003663 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003664 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003665 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003666 }
3667 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003668#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003669
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003670 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00003671 * in order to return, no direct "return" statements please.
3672 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003673
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003674////TODO: ctrl-Z handling needs re-thinking and re-testing
Denis Vlasenkod5762932009-03-31 11:22:57 +00003675
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003676#if ENABLE_HUSH_JOB
3677 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3678 * We are saving state before entering outermost list ("while...done")
3679 * so that ctrl-Z will correctly background _entire_ outermost list,
3680 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003681 if (++G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003682 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003683 /* ctrl-Z forked and we are parent; or ctrl-C.
3684 * Sighandler has longjmped us here */
3685 signal(SIGINT, SIG_IGN);
3686 signal(SIGTSTP, SIG_IGN);
3687 /* Restore level (we can be coming from deep inside
3688 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003689 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003690#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00003691 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003692 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003693 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003694 }
3695#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003696//// if (G.ctrl_z_flag) {
3697//// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3698//// * Remember this child as background job */
3699//// insert_bg_job(pi);
3700//// } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003701 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00003702 bb_putchar('\n');
Denis Vlasenkod5762932009-03-31 11:22:57 +00003703//// }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00003704 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003705 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003706 rcode = 0;
3707 goto ret;
3708 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00003709//// /* ctrl-Z handler will store pid etc in pi */
3710//// G.toplevel_list = pi;
3711//// G.ctrl_z_flag = 0;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003712#if ENABLE_FEATURE_SH_STANDALONE
3713 G.nofork_save.saved = 0; /* in case we will run a nofork later */
3714#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003715//// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3716//// signal(SIGINT, handler_ctrl_c);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003717 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00003718#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003719
Denis Vlasenko0e151382009-04-06 18:40:31 +00003720#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003721 rword = RES_NONE;
3722 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003723#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003724 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003725 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003726
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003727 /* Go through list of pipes, (maybe) executing them. */
3728 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00003729 if (G.flag_SIGINT)
3730 break;
3731
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003732 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003733 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3734 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00003735#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00003736 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003737 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00003738 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003739 /* start of a loop: remember where loop starts */
3740 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003741 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003742 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003743#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003744 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003745 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003746 if ((rcode == 0 && last_followup == PIPE_OR)
3747 || (rcode != 0 && last_followup == PIPE_AND)
3748 ) {
3749 /* It is "<true> || CMD" or "<false> && CMD"
3750 * and we should not execute CMD */
3751 debug_printf_exec("skipped cmd because of || or &&\n");
3752 last_followup = pi->followup;
3753 continue;
3754 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003755 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003756 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003757 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00003758#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003759 if (cond_code) {
3760 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00003761 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003762 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003763 /* "if <false> THEN cmd": skip cmd */
3764 continue;
3765 }
3766 } else {
3767 if (rword == RES_ELSE || rword == RES_ELIF) {
3768 /* "if <true> then ... ELSE/ELIF cmd":
3769 * skip cmd and all following ones */
3770 break;
3771 }
3772 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003773#endif
3774#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003775 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003776 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003777 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003778
3779 static const char encoded_dollar_at[] ALIGN1 = {
3780 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3781 }; /* encoded representation of "$@" */
3782 static const char *const encoded_dollar_at_argv[] = {
3783 encoded_dollar_at, NULL
3784 }; /* argv list with one element: "$@" */
3785 char **vals;
3786
3787 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003788 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003789 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003790 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003791 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003792 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003793 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003794 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003795 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003796 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003797 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003798 debug_print_strings("for_list made from", vals);
3799 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003800 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003801 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003802 for_varname = pi->cmds[0].argv[0];
3803 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003804 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003805 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003806 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00003807 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003808 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003809 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003810 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003811 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003812 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003813 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003814 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003815 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003816 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3817 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003818 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003819 if (rword == RES_IN) {
3820 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3821 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003822 if (rword == RES_DONE) {
3823 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003824 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003825#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003826#if ENABLE_HUSH_CASE
3827 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003828 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003829 continue;
3830 }
3831 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003832 char **argv;
3833
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003834 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3835 break;
3836 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003837 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003838 while (*argv) {
3839 char *pattern = expand_string_to_string(*argv);
3840 /* TODO: which FNM_xxx flags to use? */
3841 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3842 free(pattern);
3843 if (cond_code == 0) { /* match! we will execute this branch */
3844 free(case_word); /* make future "word)" stop */
3845 case_word = NULL;
3846 break;
3847 }
3848 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003849 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003850 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003851 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003852 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003853 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003854 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003855 }
3856#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003857 /* Just pressing <enter> in shell should check for jobs.
3858 * OTOH, in non-interactive shell this is useless
3859 * and only leads to extra job checks */
3860 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003861 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00003862 goto check_jobs_and_continue;
3863 continue;
3864 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003865
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003866 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00003867 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003868 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003869 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003870 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003871 {
3872 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003873#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00003874 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003875#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003876 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3877 if (r != -1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003878 /* We only ran a builtin: rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003879 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003880 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003881 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003882 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003883#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003884 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003885 if (G.flag_break_continue) {
3886 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003887 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003888 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003889 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003890 G.depth_break_continue--;
3891 if (G.depth_break_continue == 0)
3892 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003893 /* else: e.g. "continue 2" should *break* once, *then* continue */
3894 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003895 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003896 goto check_jobs_and_break;
3897 /* "continue": simulate end of loop */
3898 rword = RES_DONE;
3899 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003900 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003901#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003902 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003903 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003904 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003905 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3906 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003907 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003908#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003909 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003910 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003911#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003912 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003913 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003914 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003915#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003916 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003917 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003918 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003919 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003920 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003921 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003922#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003923 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003924 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003925 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003926 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003927 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003928 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003929 }
3930 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003931
3932 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00003933#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003934 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003935 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00003936#endif
3937#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003938 /* Beware of "while false; true; do ..."! */
3939 if (pi->next && pi->next->res_word == RES_DO) {
3940 if (rword == RES_WHILE) {
3941 if (rcode) {
3942 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003943 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003944 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3945 goto check_jobs_and_break;
3946 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003947 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003948 if (rword == RES_UNTIL) {
3949 if (!rcode) {
3950 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003951 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003952 checkjobs(NULL);
3953 break;
3954 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003955 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003956 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003957#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00003958
3959 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00003960 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003961 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003962
3963#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00003964//// if (G.ctrl_z_flag) {
3965//// /* ctrl-Z forked somewhere in the past, we are the child,
3966//// * and now we completed running the list. Exit. */
3967//////TODO: _exit?
3968//// exit(rcode);
3969//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003970 ret:
Denis Vlasenkod5762932009-03-31 11:22:57 +00003971 G.run_list_level--;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003972//// if (!G.run_list_level && G_interactive_fd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00003973//// signal(SIGTSTP, SIG_IGN);
3974//// signal(SIGINT, SIG_IGN);
3975//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003976#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003977#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003978 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003979 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003980 free(for_list);
3981#endif
3982#if ENABLE_HUSH_CASE
3983 free(case_word);
3984#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003985 debug_leave();
3986 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003987 return rcode;
3988}
3989
Eric Andersen25f27032001-04-26 23:22:31 +00003990/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003991static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003992{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003993 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003994 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003995 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003996 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003997 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003998 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003999 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004000 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004001 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004002 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004003 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004004 return rcode;
4005}
4006
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004007
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004008static struct pipe *new_pipe(void)
4009{
Eric Andersen25f27032001-04-26 23:22:31 +00004010 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004011 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004012 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004013 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004014 return pi;
4015}
4016
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004017/* Command (member of a pipe) is complete. The only possible error here
4018 * is out of memory, in which case xmalloc exits. */
4019static int done_command(struct parse_context *ctx)
4020{
4021 /* The command is really already in the pipe structure, so
4022 * advance the pipe counter and make a new, null command. */
4023 struct pipe *pi = ctx->pipe;
4024 struct command *command = ctx->command;
4025
4026 if (command) {
4027 if (command->group == NULL
4028 && command->argv == NULL
4029 && command->redirects == NULL
4030 ) {
4031 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004032 memset(command, 0, sizeof(*command)); /* paranoia */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004033 return pi->num_cmds;
4034 }
4035 pi->num_cmds++;
4036 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004037 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004038 } else {
4039 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4040 }
4041
4042 /* Only real trickiness here is that the uncommitted
4043 * command structure is not counted in pi->num_cmds. */
4044 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4045 command = &pi->cmds[pi->num_cmds];
4046 memset(command, 0, sizeof(*command));
4047
4048 ctx->command = command;
4049 /* but ctx->pipe and ctx->list_head remain unchanged */
4050
4051 return pi->num_cmds; /* used only for 0/nonzero check */
4052}
4053
4054static void done_pipe(struct parse_context *ctx, pipe_style type)
4055{
4056 int not_null;
4057
4058 debug_printf_parse("done_pipe entered, followup %d\n", type);
4059 /* Close previous command */
4060 not_null = done_command(ctx);
4061 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004062#if HAS_KEYWORDS
4063 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4064 ctx->ctx_inverted = 0;
4065 ctx->pipe->res_word = ctx->ctx_res_w;
4066#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004067
4068 /* Without this check, even just <enter> on command line generates
4069 * tree of three NOPs (!). Which is harmless but annoying.
4070 * IOW: it is safe to do it unconditionally.
4071 * RES_NONE case is for "for a in; do ..." (empty IN set)
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004072 * and other cases to work. */
4073 if (not_null
4074#if HAS_KEYWORDS
4075 || ctx->ctx_res_w == RES_FI
4076 || ctx->ctx_res_w == RES_DONE
4077 || ctx->ctx_res_w == RES_FOR
4078 || ctx->ctx_res_w == RES_IN
4079 || ctx->ctx_res_w == RES_ESAC
4080#endif
4081 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004082 struct pipe *new_p;
4083 debug_printf_parse("done_pipe: adding new pipe: "
4084 "not_null:%d ctx->ctx_res_w:%d\n",
4085 not_null, ctx->ctx_res_w);
4086 new_p = new_pipe();
4087 ctx->pipe->next = new_p;
4088 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004089 /* RES_THEN, RES_DO etc are "sticky" -
4090 * they remain set for commands inside if/while.
4091 * This is used to control execution.
4092 * RES_FOR and RES_IN are NOT sticky (needed to support
4093 * cases where variable or value happens to match a keyword):
4094 */
4095#if ENABLE_HUSH_LOOPS
4096 if (ctx->ctx_res_w == RES_FOR
4097 || ctx->ctx_res_w == RES_IN)
4098 ctx->ctx_res_w = RES_NONE;
4099#endif
4100#if ENABLE_HUSH_CASE
4101 if (ctx->ctx_res_w == RES_MATCH)
4102 ctx->ctx_res_w = RES_CASEI;
4103#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004104 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004105 /* Create the memory for command, roughly:
4106 * ctx->pipe->cmds = new struct command;
4107 * ctx->command = &ctx->pipe->cmds[0];
4108 */
4109 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004110 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004111 }
4112 debug_printf_parse("done_pipe return\n");
4113}
4114
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004115static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004116{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004117 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004118 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004119 /* Create the memory for command, roughly:
4120 * ctx->pipe->cmds = new struct command;
4121 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004122 */
4123 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004124}
4125
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004126/* If a reserved word is found and processed, parse context is modified
4127 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004128 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004129#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004130struct reserved_combo {
4131 char literal[6];
4132 unsigned char res;
4133 unsigned char assignment_flag;
4134 int flag;
4135};
4136enum {
4137 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004138#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004139 FLAG_IF = (1 << RES_IF ),
4140 FLAG_THEN = (1 << RES_THEN ),
4141 FLAG_ELIF = (1 << RES_ELIF ),
4142 FLAG_ELSE = (1 << RES_ELSE ),
4143 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004144#endif
4145#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004146 FLAG_FOR = (1 << RES_FOR ),
4147 FLAG_WHILE = (1 << RES_WHILE),
4148 FLAG_UNTIL = (1 << RES_UNTIL),
4149 FLAG_DO = (1 << RES_DO ),
4150 FLAG_DONE = (1 << RES_DONE ),
4151 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004152#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004153#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004154 FLAG_MATCH = (1 << RES_MATCH),
4155 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004156#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004157 FLAG_START = (1 << RES_XXXX ),
4158};
4159
4160static const struct reserved_combo* match_reserved_word(o_string *word)
4161{
Eric Andersen25f27032001-04-26 23:22:31 +00004162 /* Mostly a list of accepted follow-up reserved words.
4163 * FLAG_END means we are done with the sequence, and are ready
4164 * to turn the compound list into a command.
4165 * FLAG_START means the word must start a new compound list.
4166 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004167 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004168#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004169 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4170 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4171 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4172 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4173 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4174 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004175#endif
4176#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004177 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4178 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4179 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4180 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4181 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4182 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004183#endif
4184#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004185 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4186 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004187#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004188 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004189 const struct reserved_combo *r;
4190
4191 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4192 if (strcmp(word->data, r->literal) == 0)
4193 return r;
4194 }
4195 return NULL;
4196}
4197static int reserved_word(o_string *word, struct parse_context *ctx)
4198{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004199#if ENABLE_HUSH_CASE
4200 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004201 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004202 };
4203#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004204 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004205
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004206 r = match_reserved_word(word);
4207 if (!r)
4208 return 0;
4209
4210 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004211#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004212 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
4213 /* "case word IN ..." - IN part starts first match part */
4214 r = &reserved_match;
4215 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004216#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004217 if (r->flag == 0) { /* '!' */
4218 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004219 syntax_error("! ! command");
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004220 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00004221 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004222 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004223 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004224 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004225 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004226 struct parse_context *old;
4227 old = xmalloc(sizeof(*old));
4228 debug_printf_parse("push stack %p\n", old);
4229 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004230 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004231 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004232 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004233 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004234 ctx->ctx_res_w = RES_SNTX;
4235 return 1;
4236 }
4237 ctx->ctx_res_w = r->res;
4238 ctx->old_flag = r->flag;
4239 if (ctx->old_flag & FLAG_END) {
4240 struct parse_context *old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004241 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004242 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004243 old = ctx->stack;
4244 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004245 old->command->grp_type = GRP_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004246#if !BB_MMU
4247 o_addstr(&old->as_string, ctx->as_string.data);
4248 o_free_unsafe(&ctx->as_string);
4249 old->command->group_as_string = xstrdup(old->as_string.data);
4250 debug_printf_parse("pop, remembering as:'%s'\n",
4251 old->command->group_as_string);
4252#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004253 *ctx = *old; /* physical copy */
4254 free(old);
4255 }
4256 word->o_assignment = r->assignment_flag;
4257 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004258}
Denis Vlasenko06810332007-05-21 23:30:54 +00004259#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004260
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004261/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004262 * Normal return is 0. Syntax errors return 1.
4263 * Note: on return, word is reset, but not o_free'd!
4264 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004265static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004266{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004267 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004268
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004269 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004270 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004271 debug_printf_parse("done_word return 0: true null, ignored\n");
4272 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004273 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004274
Eric Andersen25f27032001-04-26 23:22:31 +00004275 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004276 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4277 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004278 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4279 * "2.7 Redirection
4280 * ...the word that follows the redirection operator
4281 * shall be subjected to tilde expansion, parameter expansion,
4282 * command substitution, arithmetic expansion, and quote
4283 * removal. Pathname expansion shall not be performed
4284 * on the word by a non-interactive shell; an interactive
4285 * shell may perform it, but shall do so only when
4286 * the expansion would result in one word."
4287 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004288 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004289 /* Cater for >\file case:
4290 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4291 * Same with heredocs:
4292 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4293 */
4294 unbackslash(ctx->pending_redirect->rd_filename);
4295 /* Is it <<"HEREDOC"? */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004296 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4297 && word->o_quoted
4298 ) {
4299 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4300 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004301 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004302 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004303 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004304 /* If this word wasn't an assignment, next ones definitely
4305 * can't be assignments. Even if they look like ones. */
4306 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4307 && word->o_assignment != WORD_IS_KEYWORD
4308 ) {
4309 word->o_assignment = NOT_ASSIGNMENT;
4310 } else {
4311 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4312 command->assignment_cnt++;
4313 word->o_assignment = MAYBE_ASSIGNMENT;
4314 }
4315
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004316 if (command->group) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004317 /* "{ echo foo; } echo bar" - bad */
4318 /* NB: bash allows e.g.:
4319 * if true; then { echo foo; } fi
4320 * while if false; then false; fi do break; done
4321 * and disallows:
4322 * while if false; then false; fi; do; break; done
4323 * TODO? */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004324 syntax_error_at(word->data);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004325 debug_printf_parse("done_word return 1: syntax error, "
4326 "groups and arglists don't mix\n");
Denis Vlasenko395ae452008-07-14 06:29:38 +00004327 return 1;
4328 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004329#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004330# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004331 if (ctx->ctx_dsemicolon
4332 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4333 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004334 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004335 /* ctx->ctx_res_w = RES_MATCH; */
4336 ctx->ctx_dsemicolon = 0;
4337 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004338# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004339 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004340# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004341 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4342 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004343# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004344 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004345 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
4346 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004347 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004348 debug_printf_parse("done_word return %d\n",
4349 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004350 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004351 }
Eric Andersen25f27032001-04-26 23:22:31 +00004352 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004353#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004354 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004355 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4356 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004357 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004358 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004359 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004360 char *p = word->data;
4361 while (p[0] == SPECIAL_VAR_SYMBOL
4362 && (p[1] & 0x7f) == '@'
4363 && p[2] == SPECIAL_VAR_SYMBOL
4364 ) {
4365 p += 3;
4366 }
4367 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004368 /* saw no "$@", or not only "$@" but some
4369 * real text is there too */
4370 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004371 * e.g. "", $empty"" etc to not disappear */
4372 o_addchr(word, SPECIAL_VAR_SYMBOL);
4373 o_addchr(word, SPECIAL_VAR_SYMBOL);
4374 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004375 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004376 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004377//SEGV, but good idea.
4378// command->argv = add_string_to_strings(command->argv, word->data);
4379// word->data = NULL;
4380// word->length = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004381 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004382 }
Eric Andersen25f27032001-04-26 23:22:31 +00004383
Denis Vlasenko06810332007-05-21 23:30:54 +00004384#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004385 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004386 if (word->o_quoted
4387 || !is_well_formed_var_name(command->argv[0], '\0')
4388 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004389 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004390 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004391 return 1;
4392 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004393 /* Force FOR to have just one word (variable name) */
4394 /* NB: basically, this makes hush see "for v in ..."
4395 * syntax as if it is "for v; in ...". FOR and IN become
4396 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004397 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004398 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004399#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004400#if ENABLE_HUSH_CASE
4401 /* Force CASE to have just one word */
4402 if (ctx->ctx_res_w == RES_CASE) {
4403 done_pipe(ctx, PIPE_SEQ);
4404 }
4405#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004406
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004407 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004408
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004409 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004410 return 0;
4411}
4412
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004413
4414/* Peek ahead in the input to find out if we have a "&n" construct,
4415 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004416 * Return:
4417 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4418 * REDIRFD_SYNTAX_ERR if syntax error,
4419 * REDIRFD_TO_FILE if no & was seen,
4420 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004421 */
4422#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004423#define parse_redir_right_fd(as_string, input) \
4424 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004425#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004426static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004427{
4428 int ch, d, ok;
4429
4430 ch = i_peek(input);
4431 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004432 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004433
4434 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004435 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004436 ch = i_peek(input);
4437 if (ch == '-') {
4438 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004439 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004440 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004441 }
4442 d = 0;
4443 ok = 0;
4444 while (ch != EOF && isdigit(ch)) {
4445 d = d*10 + (ch-'0');
4446 ok = 1;
4447 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004448 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004449 ch = i_peek(input);
4450 }
4451 if (ok) return d;
4452
4453//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4454
4455 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004456 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004457}
4458
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004459/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004460 */
4461static int parse_redirect(struct parse_context *ctx,
4462 int fd,
4463 redir_type style,
4464 struct in_str *input)
4465{
4466 struct command *command = ctx->command;
4467 struct redir_struct *redir;
4468 struct redir_struct **redirp;
4469 int dup_num;
4470
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004471 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004472 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004473 /* Check for a '>&1' type redirect */
4474 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4475 if (dup_num == REDIRFD_SYNTAX_ERR)
4476 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004477 } else {
4478 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004479 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004480 if (dup_num) { /* <<-... */
4481 ch = i_getch(input);
4482 nommu_addchr(&ctx->as_string, ch);
4483 ch = i_peek(input);
4484 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004485 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004486
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004487 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004488 int ch = i_peek(input);
4489 if (ch == '|') {
4490 /* >|FILE redirect ("clobbering" >).
4491 * Since we do not support "set -o noclobber" yet,
4492 * >| and > are the same for now. Just eat |.
4493 */
4494 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004495 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004496 }
4497 }
4498
4499 /* Create a new redir_struct and append it to the linked list */
4500 redirp = &command->redirects;
4501 while ((redir = *redirp) != NULL) {
4502 redirp = &(redir->next);
4503 }
4504 *redirp = redir = xzalloc(sizeof(*redir));
4505 /* redir->next = NULL; */
4506 /* redir->rd_filename = NULL; */
4507 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004508 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004509
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004510 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4511 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004512
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004513 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004514 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004515 /* Erik had a check here that the file descriptor in question
4516 * is legit; I postpone that to "run time"
4517 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004518 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4519 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004520 } else {
4521 /* Set ctx->pending_redirect, so we know what to do at the
4522 * end of the next parsed word. */
4523 ctx->pending_redirect = redir;
4524 }
4525 return 0;
4526}
4527
Eric Andersen25f27032001-04-26 23:22:31 +00004528/* If a redirect is immediately preceded by a number, that number is
4529 * supposed to tell which file descriptor to redirect. This routine
4530 * looks for such preceding numbers. In an ideal world this routine
4531 * needs to handle all the following classes of redirects...
4532 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4533 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4534 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4535 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004536 *
4537 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4538 * "2.7 Redirection
4539 * ... If n is quoted, the number shall not be recognized as part of
4540 * the redirection expression. For example:
4541 * echo \2>a
4542 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004543 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004544 *
4545 * A -1 return means no valid number was found,
4546 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004547 */
4548static int redirect_opt_num(o_string *o)
4549{
4550 int num;
4551
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004552 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004553 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004554 num = bb_strtou(o->data, NULL, 10);
4555 if (errno || num < 0)
4556 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004557 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004558 return num;
4559}
4560
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004561#if BB_MMU
4562#define fetch_till_str(as_string, input, word, skip_tabs) \
4563 fetch_till_str(input, word, skip_tabs)
4564#endif
4565static char *fetch_till_str(o_string *as_string,
4566 struct in_str *input,
4567 const char *word,
4568 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004569{
4570 o_string heredoc = NULL_O_STRING;
4571 int past_EOL = 0;
4572 int ch;
4573
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004574 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004575 while (1) {
4576 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004577 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004578 if (ch == '\n') {
4579 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4580 heredoc.data[past_EOL] = '\0';
4581 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4582 return heredoc.data;
4583 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004584 do {
4585 o_addchr(&heredoc, ch);
4586 past_EOL = heredoc.length;
4587 jump_in:
4588 do {
4589 ch = i_getch(input);
4590 nommu_addchr(as_string, ch);
4591 } while (skip_tabs && ch == '\t');
4592 } while (ch == '\n');
4593 }
4594 if (ch == EOF) {
4595 o_free_unsafe(&heredoc);
4596 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004597 }
4598 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004599 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004600 }
4601}
4602
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004603/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4604 * and load them all. There should be exactly heredoc_cnt of them.
4605 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004606static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4607{
4608 struct pipe *pi = ctx->list_head;
4609
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004610 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004611 int i;
4612 struct command *cmd = pi->cmds;
4613
4614 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4615 pi->num_cmds,
4616 cmd->argv ? cmd->argv[0] : "NONE");
4617 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004618 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004619
4620 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4621 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004622 while (redir) {
4623 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004624 char *p;
4625
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004626 redir->rd_type = REDIRECT_HEREDOC2;
4627 /* redir->dup is (ab)used to indicate <<- */
4628 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004629 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004630 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004631 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004632 return 1;
4633 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004634 free(redir->rd_filename);
4635 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004636 heredoc_cnt--;
4637 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004638 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004639 }
4640 cmd++;
4641 }
4642 pi = pi->next;
4643 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004644#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004645 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004646 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004647 bb_error_msg_and_die("heredoc BUG 2");
4648#endif
4649 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004650}
4651
4652
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004653#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004654static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004655{
4656 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004657 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004658
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00004659 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00004660 pid = BB_MMU ? fork() : vfork();
4661 if (pid < 0)
4662 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004663
Denis Vlasenko05743d72008-02-10 12:10:08 +00004664 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004665 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004666 /* Process substitution is not considered to be usual
4667 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004668 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4669 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00004670 bb_signals(0
4671 + (1 << SIGTSTP)
4672 + (1 << SIGTTIN)
4673 + (1 << SIGTTOU)
4674 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004675 close(channel[0]); /* NB: close _first_, then move fd! */
4676 xmove_fd(channel[1], 1);
4677 /* Prevent it from trying to handle ctrl-z etc */
4678 USE_HUSH_JOB(G.run_list_level = 1;)
4679#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004680 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004681 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004682 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004683#else
4684 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00004685 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4686 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004687 * echo OK
4688 */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004689 re_execute_shell(s,
4690 G.global_argv[0],
4691 G.global_argv + 1);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004692#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004693 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004694
4695 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004696 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004697 clean_up_after_re_execute();
Eric Andersen25f27032001-04-26 23:22:31 +00004698 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004699 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00004700 return pf;
4701}
4702
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004703/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004704static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004705{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004706 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004707 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004708 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004709
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004710 pf = generate_stream_from_string(s);
4711 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00004712 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004713 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00004714
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004715 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004716 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004717 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004718 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004719 if (ch == '\n') {
4720 eol_cnt++;
4721 continue;
4722 }
4723 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004724 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004725 eol_cnt--;
4726 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004727 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004728 }
4729
4730 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004731 /* Note: we got EOF, and we just close the read end of the pipe.
4732 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004733 * Try these:
4734 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4735 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004736 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004737 fclose(pf);
4738 debug_printf("closed FILE from child. return 0\n");
4739 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004740}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004741#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004742
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004743static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004744 struct in_str *input, int ch)
4745{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004746 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004747 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004748 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004749 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004750 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004751 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004752
4753 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004754#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004755 if (ch == '(' && !dest->o_quoted) {
4756 if (dest->length)
4757 done_word(dest, ctx);
4758 if (!command->argv)
4759 goto skip; /* (... */
4760 if (command->argv[1]) { /* word word ... (... */
4761 syntax_error_unexpected_ch('(');
4762 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004763 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004764 /* it is "word(..." or "word (..." */
4765 do
4766 ch = i_getch(input);
4767 while (ch == ' ' || ch == '\t');
4768 if (ch != ')') {
4769 syntax_error_unexpected_ch(ch);
4770 return 1;
4771 }
4772 nommu_addchr(&ctx->as_string, ch);
4773 do
4774 ch = i_getch(input);
4775 while (ch == ' ' || ch == '\t' || ch == '\n');
4776 if (ch != '{') {
4777 syntax_error_unexpected_ch(ch);
4778 return 1;
4779 }
4780 nommu_addchr(&ctx->as_string, ch);
4781 command->grp_type = GRP_FUNCTION;
4782 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004783 }
4784#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004785 if (command->argv /* word [word]{... */
4786 || dest->length /* word{... */
4787 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004788 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004789 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004790 debug_printf_parse("parse_group return 1: "
4791 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004792 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004793 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004794
4795#if ENABLE_HUSH_FUNCTIONS
4796 skip:
4797#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004798 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004799 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004800 endch = ')';
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004801 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00004802 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004803
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004804 {
4805#if !BB_MMU
4806 char *as_string = NULL;
4807#endif
4808 pipe_list = parse_stream(&as_string, input, endch);
4809#if !BB_MMU
4810 if (as_string)
4811 o_addstr(&ctx->as_string, as_string);
4812#endif
4813 /* empty ()/{} or parse error? */
4814 if (!pipe_list || pipe_list == ERR_PTR) {
4815#if !BB_MMU
4816 free(as_string);
4817#endif
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004818 syntax_error(NULL);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004819 debug_printf_parse("parse_group return 1: "
4820 "parse_stream returned %p\n", pipe_list);
4821 return 1;
4822 }
4823 command->group = pipe_list;
4824#if !BB_MMU
4825 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4826 command->group_as_string = as_string;
4827 debug_printf_parse("end of group, remembering as:'%s'\n",
4828 command->group_as_string);
4829#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004830 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004831 debug_printf_parse("parse_group return 0\n");
4832 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004833 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004834}
4835
Mike Frysinger98c52642009-04-02 10:02:37 +00004836#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004837/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004838static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004839/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004840static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004841{
4842 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004843 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004844 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004845 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004846 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004847 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004848 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004849 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004850 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004851 }
4852}
4853/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004854static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004855{
4856 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004857 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004858 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004859 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004860 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004861 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004862 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004863 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004864 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004865 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004866 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004867 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004868 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004869 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004870 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004871 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004872 continue;
4873 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004874 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004875 }
4876}
4877/* Process `cmd` - copy contents until "`" is seen. Complicated by
4878 * \` quoting.
4879 * "Within the backquoted style of command substitution, backslash
4880 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4881 * The search for the matching backquote shall be satisfied by the first
4882 * backquote found without a preceding backslash; during this search,
4883 * if a non-escaped backquote is encountered within a shell comment,
4884 * a here-document, an embedded command substitution of the $(command)
4885 * form, or a quoted string, undefined results occur. A single-quoted
4886 * or double-quoted string that begins, but does not end, within the
4887 * "`...`" sequence produces undefined results."
4888 * Example Output
4889 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4890 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004891static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004892{
4893 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004894 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004895 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004896 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004897 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004898 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004899 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004900 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004901 if (ch == '\\') {
4902 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004903 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004904 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004905 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004906 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004907 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004908 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004909 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004910 ch = ch2;
4911 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004912 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004913 }
4914}
4915/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4916 * quoting and nested ()s.
4917 * "With the $(command) style of command substitution, all characters
4918 * following the open parenthesis to the matching closing parenthesis
4919 * constitute the command. Any valid shell script can be used for command,
4920 * except a script consisting solely of redirections which produces
4921 * unspecified results."
4922 * Example Output
4923 * echo $(echo '(TEST)' BEST) (TEST) BEST
4924 * echo $(echo 'TEST)' BEST) TEST) BEST
4925 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4926 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004927static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004928{
4929 int count = 0;
4930 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004931 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004932 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004933 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004934 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004935 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004936 if (ch == '(')
4937 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004938 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00004939 if (--count < 0) {
4940 if (!dbl)
4941 break;
4942 if (i_peek(input) == ')') {
4943 i_getch(input);
4944 break;
4945 }
4946 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004947 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004948 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004949 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004950 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004951 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004952 continue;
4953 }
4954 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004955 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004956 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004957 continue;
4958 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004959 if (ch == '\\') {
4960 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004961 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004962 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004963 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004964 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004965 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004966 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004967 continue;
4968 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004969 }
4970}
Mike Frysinger98c52642009-04-02 10:02:37 +00004971#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004972
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004973/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004974#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004975#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004976 handle_dollar(dest, input)
4977#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004978static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004979 o_string *dest,
4980 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00004981{
Mike Frysinger6379bb42009-03-28 18:55:03 +00004982 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004983 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004984 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004985
4986 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004987 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004988 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004989 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004990 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004991 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004992 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004993 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004994 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004995 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004996 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004997 if (!isalnum(ch) && ch != '_')
4998 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004999 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005000 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005001 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005002 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005003 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005004 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005005 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005006 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005007 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005008 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005009 o_addchr(dest, ch | quote_mask);
5010 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005011 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005012 case '$': /* pid */
5013 case '!': /* last bg pid */
5014 case '?': /* last exit code */
5015 case '#': /* number of args */
5016 case '*': /* args */
5017 case '@': /* args */
5018 goto make_one_char_var;
5019 case '{': {
5020 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005021
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005022 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005023 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005024 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005025 /* XXX maybe someone will try to escape the '}' */
5026 expansion = 0;
5027 first_char = true;
5028 all_digits = false;
5029 while (1) {
5030 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005031 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005032 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00005033 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00005034
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005035 if (first_char) {
5036 if (ch == '#')
5037 /* ${#var}: length of var contents */
5038 goto char_ok;
5039 else if (isdigit(ch)) {
5040 all_digits = true;
5041 goto char_ok;
5042 }
5043 }
5044
5045 if (expansion < 2
5046 && ( (all_digits && !isdigit(ch))
5047 || (!all_digits && !isalnum(ch) && ch != '_')
5048 )
5049 ) {
5050 /* handle parameter expansions
5051 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5052 */
5053 if (first_char)
5054 goto case_default;
5055 switch (ch) {
5056 case ':': /* null modifier */
5057 if (expansion == 0) {
5058 debug_printf_parse(": null modifier\n");
5059 ++expansion;
5060 break;
5061 }
5062 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005063 case '#': /* remove prefix */
5064 case '%': /* remove suffix */
5065 if (expansion == 0) {
5066 debug_printf_parse(": remove suffix/prefix\n");
5067 expansion = 2;
5068 break;
5069 }
5070 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005071 case '-': /* default value */
5072 case '=': /* assign default */
5073 case '+': /* alternative */
5074 case '?': /* error indicate */
5075 debug_printf_parse(": parameter expansion\n");
5076 expansion = 2;
5077 break;
5078 default:
5079 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005080 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005081 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5082 return 1;
5083 }
5084 }
5085 char_ok:
5086 debug_printf_parse(": '%c'\n", ch);
5087 o_addchr(dest, ch | quote_mask);
5088 quote_mask = 0;
5089 first_char = false;
5090 }
5091 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5092 break;
5093 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005094#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005095 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005096# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005097 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005098# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005099 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005100 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005101# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005102 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005103 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005104 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005105 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5106 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005107# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005108 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005109# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005110 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005111# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005112 if (as_string) {
5113 o_addstr(as_string, dest->data + pos);
5114 o_addchr(as_string, ')');
5115 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005116 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005117# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005118 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005119 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005120 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005121# endif
5122# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005123 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5124 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005125# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005126 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005127# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005128 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005129# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005130 if (as_string) {
5131 o_addstr(as_string, dest->data + pos);
5132 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005133 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005134# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005135 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005136# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005137 break;
5138 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005139#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005140 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005141 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005142 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005143 ch = i_peek(input);
5144 if (isalnum(ch)) { /* it's $_name or $_123 */
5145 ch = '_';
5146 goto make_var;
5147 }
5148 /* else: it's $_ */
5149 /* TODO: */
5150 /* $_ Shell or shell script name; or last cmd name */
5151 /* $- Option flags set by set builtin or shell options (-i etc) */
5152 default:
5153 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005154 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005155 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005156 return 0;
5157}
5158
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005159#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005160#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005161 parse_stream_dquoted(dest, input, dquote_end)
5162#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005163static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005164 o_string *dest,
5165 struct in_str *input,
5166 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005167{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005168 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005169 int next;
5170
5171 again:
5172 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005173 if (ch != EOF)
5174 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005175 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005176 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005177 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005178 debug_printf_parse("parse_stream_dquoted return 0\n");
5179 return 0;
5180 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005181 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005182 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005183 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005184 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005185 }
5186 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005187 if (ch != '\n') {
5188 next = i_peek(input);
5189 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005190 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5191 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005192 if (ch == '\\') {
5193 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005194 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005195 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005196 }
5197 /* bash:
5198 * "The backslash retains its special meaning [in "..."]
5199 * only when followed by one of the following characters:
5200 * $, `, ", \, or <newline>. A double quote may be quoted
5201 * within double quotes by preceding it with a backslash.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005202 */
5203 if (strchr("$`\"\\", next) != NULL) {
5204 o_addqchr(dest, i_getch(input));
5205 } else {
5206 o_addqchr(dest, '\\');
5207 }
5208 goto again;
5209 }
5210 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005211 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005212 debug_printf_parse("parse_stream_dquoted return 1: "
5213 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005214 return 1;
5215 }
5216 goto again;
5217 }
5218#if ENABLE_HUSH_TICK
5219 if (ch == '`') {
5220 //int pos = dest->length;
5221 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5222 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005223 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005224 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5225 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005226 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005227 }
5228#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005229 o_addQchr(dest, ch);
5230 if (ch == '='
5231 && (dest->o_assignment == MAYBE_ASSIGNMENT
5232 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005233 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005234 ) {
5235 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5236 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005237 goto again;
5238}
5239
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005240/*
5241 * Scan input until EOF or end_trigger char.
5242 * Return a list of pipes to execute, or NULL on EOF
5243 * or if end_trigger character is met.
5244 * On syntax error, exit is shell is not interactive,
5245 * reset parsing machinery and start parsing anew,
5246 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005247 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005248static struct pipe *parse_stream(char **pstring,
5249 struct in_str *input,
5250 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005251{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005252 struct parse_context ctx;
5253 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005254 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005255 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005256
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005257 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005258 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005259 * found. When recursing, quote state is passed in via dest->o_escape.
5260 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005261 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5262 end_trigger ? : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005263 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005264
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005265 G.ifs = get_local_var_value("IFS");
5266 if (G.ifs == NULL)
5267 G.ifs = " \t\n";
5268
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005269 reset:
5270#if ENABLE_HUSH_INTERACTIVE
5271 input->promptmode = 0; /* PS1 */
5272#endif
5273 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5274 initialize_context(&ctx);
5275 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005276 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005277 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005278 const char *is_ifs;
5279 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005280 int ch;
5281 int next;
5282 int redir_fd;
5283 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005284
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005285 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005286 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005287 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005288 goto parse_error;
5289 }
5290 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005291 is_in_dquote = 0;
5292 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005293 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005294 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5295 ch, ch, dest.o_escape);
5296 if (ch == EOF) {
5297 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005298
5299 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005300 syntax_error_unterm_str("here document");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005301 xfunc_die();
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005302 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005303 if (done_word(&dest, &ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005304 xfunc_die();
Denis Vlasenko55789c62008-06-18 16:30:42 +00005305 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005306 o_free(&dest);
5307 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005308 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005309 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005310 /* (this makes bare "&" cmd a no-op.
5311 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005312 if (pi->num_cmds == 0
5313 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5314 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005315 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005316 pi = NULL;
5317 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005318#if !BB_MMU
5319 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5320 if (pstring)
5321 *pstring = ctx.as_string.data;
5322 else
5323 o_free_unsafe(&ctx.as_string);
5324#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005325 debug_leave();
5326 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005327 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005328 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005329 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005330 is_ifs = strchr(G.ifs, ch);
5331 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5332 "\\$\"" USE_HUSH_TICK("`") /* always special */
5333 , ch);
5334
5335 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005336 o_addQchr(&dest, ch);
5337 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5338 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005339 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005340 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005341 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005342 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005343 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005344 continue;
5345 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005346
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005347 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005348 if (done_word(&dest, &ctx)) {
5349 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005350 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005351 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005352#if ENABLE_HUSH_CASE
5353 /* "case ... in <newline> word) ..." -
5354 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005355 if (ctx.command->argv == NULL
5356 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005357 ) {
5358 continue;
5359 }
5360#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005361 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005362 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005363 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5364 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005365 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005366 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005367 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005368 heredoc_cnt = 0;
5369 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005370 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005371 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005372 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005373 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005374 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005375 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005376 if (end_trigger && end_trigger == ch
5377 && (heredoc_cnt == 0 || end_trigger != ';')
5378 ) {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005379//TODO: disallow "{ cmd }" without semicolon
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005380 if (heredoc_cnt) {
5381 /* This is technically valid:
5382 * { cat <<HERE; }; echo Ok
5383 * heredoc
5384 * heredoc
5385 * heredoc
5386 * HERE
5387 * but we don't support this.
5388 * We require heredoc to be in enclosing {}/(),
5389 * if any.
5390 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005391 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005392 goto parse_error;
5393 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005394 if (done_word(&dest, &ctx)) {
5395 goto parse_error;
5396 }
5397 done_pipe(&ctx, PIPE_SEQ);
5398 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005399 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005400 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005401 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005402 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005403 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005404#if !BB_MMU
5405 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5406 if (pstring)
5407 *pstring = ctx.as_string.data;
5408 else
5409 o_free_unsafe(&ctx.as_string);
5410#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005411 debug_leave();
5412 debug_printf_parse("parse_stream return %p: "
5413 "end_trigger char found\n",
5414 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005415 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005416 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005417 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005418 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005419 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005420
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005421 next = '\0';
5422 if (ch != '\n') {
5423 next = i_peek(input);
5424 }
5425
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005426 /* Catch <, > before deciding whether this word is
5427 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5428 switch (ch) {
5429 case '>':
5430 redir_fd = redirect_opt_num(&dest);
5431 if (done_word(&dest, &ctx)) {
5432 goto parse_error;
5433 }
5434 redir_style = REDIRECT_OVERWRITE;
5435 if (next == '>') {
5436 redir_style = REDIRECT_APPEND;
5437 ch = i_getch(input);
5438 nommu_addchr(&ctx.as_string, ch);
5439 }
5440#if 0
5441 else if (next == '(') {
5442 syntax_error(">(process) not supported");
5443 goto parse_error;
5444 }
5445#endif
5446 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5447 goto parse_error;
5448 continue; /* back to top of while (1) */
5449 case '<':
5450 redir_fd = redirect_opt_num(&dest);
5451 if (done_word(&dest, &ctx)) {
5452 goto parse_error;
5453 }
5454 redir_style = REDIRECT_INPUT;
5455 if (next == '<') {
5456 redir_style = REDIRECT_HEREDOC;
5457 heredoc_cnt++;
5458 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5459 ch = i_getch(input);
5460 nommu_addchr(&ctx.as_string, ch);
5461 } else if (next == '>') {
5462 redir_style = REDIRECT_IO;
5463 ch = i_getch(input);
5464 nommu_addchr(&ctx.as_string, ch);
5465 }
5466#if 0
5467 else if (next == '(') {
5468 syntax_error("<(process) not supported");
5469 goto parse_error;
5470 }
5471#endif
5472 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5473 goto parse_error;
5474 continue; /* back to top of while (1) */
5475 }
5476
5477 if (dest.o_assignment == MAYBE_ASSIGNMENT
5478 /* check that we are not in word in "a=1 2>word b=1": */
5479 && !ctx.pending_redirect
5480 ) {
5481 /* ch is a special char and thus this word
5482 * cannot be an assignment */
5483 dest.o_assignment = NOT_ASSIGNMENT;
5484 }
5485
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005486 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00005487 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005488 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005489 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005490 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005491 if (ch == EOF || ch == '\n')
5492 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005493 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005494 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005495 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005496 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00005497 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005498 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005499 }
5500 break;
5501 case '\\':
5502 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005503 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005504 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005505 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005506 o_addchr(&dest, '\\');
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005507 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005508 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005509 o_addchr(&dest, ch);
5510 /* Example: echo Hello \2>file
5511 * we need to know that word 2 is quoted */
5512 dest.o_quoted = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005513 break;
5514 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005515 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005516 debug_printf_parse("parse_stream parse error: "
5517 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005518 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005519 }
Eric Andersen25f27032001-04-26 23:22:31 +00005520 break;
5521 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005522 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005523 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005524 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005525 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005526 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005527 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005528 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005529 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005530 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005531 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005532 if (dest.o_assignment == NOT_ASSIGNMENT)
5533 o_addqchr(&dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005534 else
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005535 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005536 }
Eric Andersen25f27032001-04-26 23:22:31 +00005537 break;
5538 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005539 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005540 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005541 if (dest.o_assignment == NOT_ASSIGNMENT)
5542 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005543 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005544#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005545 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005546#if !BB_MMU
5547 int pos;
5548#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005549 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5550 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005551#if !BB_MMU
5552 pos = dest.length;
5553#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005554 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005555#if !BB_MMU
5556 o_addstr(&ctx.as_string, dest.data + pos);
5557 o_addchr(&ctx.as_string, '`');
5558#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005559 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5560 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005561 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005562 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005563#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005564 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005565#if ENABLE_HUSH_CASE
5566 case_semi:
5567#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005568 if (done_word(&dest, &ctx)) {
5569 goto parse_error;
5570 }
5571 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005572#if ENABLE_HUSH_CASE
5573 /* Eat multiple semicolons, detect
5574 * whether it means something special */
5575 while (1) {
5576 ch = i_peek(input);
5577 if (ch != ';')
5578 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005579 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005580 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005581 if (ctx.ctx_res_w == RES_CASEI) {
5582 ctx.ctx_dsemicolon = 1;
5583 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005584 break;
5585 }
5586 }
5587#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005588 new_cmd:
5589 /* We just finished a cmd. New one may start
5590 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005591 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00005592 break;
5593 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005594 if (done_word(&dest, &ctx)) {
5595 goto parse_error;
5596 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005597 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005598 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005599 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005600 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005601 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005602 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005603 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005604 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005605 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005606 if (done_word(&dest, &ctx)) {
5607 goto parse_error;
5608 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005609#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005610 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005611 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005612#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005613 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005614 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005615 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005616 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005617 } else {
5618 /* we could pick up a file descriptor choice here
5619 * with redirect_opt_num(), but bash doesn't do it.
5620 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005621 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005622 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005623 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005624 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005625#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005626 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005627 if (ctx.ctx_res_w == RES_MATCH
5628 && ctx.command->argv == NULL /* not (word|(... */
5629 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005630 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005631 ) {
5632 continue;
5633 }
5634#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005635 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005636 if (parse_group(&dest, &ctx, input, ch) != 0) {
5637 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005638 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005639 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005640 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005641#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005642 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005643 goto case_semi;
5644#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005645 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005646 /* proper use of this character is caught by end_trigger:
5647 * if we see {, we call parse_group(..., end_trigger='}')
5648 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005649 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005650 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005651 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005652 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005653 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005654 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005655 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005656
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005657 parse_error:
5658 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005659 struct parse_context *pctx;
5660 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005661
5662 /* Clean up allocated tree.
5663 * Samples for finding leaks on syntax error recovery path.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005664 * Run them from interactive shell, watch pmap `pidof hush`.
5665 * while if false; then false; fi do break; done
5666 * (bash accepts it)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005667 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005668 * Samples to catch leaks at execution:
5669 * while if (true | {true;}); then echo ok; fi; do break; done
5670 * 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 +00005671 */
5672 pctx = &ctx;
5673 do {
5674 /* Update pipe/command counts,
5675 * otherwise freeing may miss some */
5676 done_pipe(pctx, PIPE_SEQ);
5677 debug_printf_clean("freeing list %p from ctx %p\n",
5678 pctx->list_head, pctx);
5679 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005680 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005681 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005682#if !BB_MMU
5683 o_free_unsafe(&pctx->as_string);
5684#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005685 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005686 if (pctx != &ctx) {
5687 free(pctx);
5688 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005689 IF_HAS_KEYWORDS(pctx = p2;)
5690 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005691 /* Free text, clear all dest fields */
5692 o_free(&dest);
5693 /* If we are not in top-level parse, we return,
5694 * our caller will propagate error.
5695 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005696 if (end_trigger != ';') {
5697#if !BB_MMU
5698 if (pstring)
5699 *pstring = NULL;
5700#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005701 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005702 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005703 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005704 /* Discard cached input, force prompt */
5705 input->p = NULL;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005706 USE_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005707 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005708 }
Eric Andersen25f27032001-04-26 23:22:31 +00005709}
5710
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005711/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005712 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5713 * end_trigger controls how often we stop parsing
5714 * NUL: parse all, execute, return
5715 * ';': parse till ';' or newline, execute, repeat till EOF
5716 */
5717static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005718{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005719 while (1) {
5720 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005721
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005722 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005723 if (!pipe_list) /* EOF */
5724 break;
5725 debug_print_tree(pipe_list, 0);
5726 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5727 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005728 }
Eric Andersen25f27032001-04-26 23:22:31 +00005729}
5730
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005731static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005732{
5733 struct in_str input;
5734 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005735 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005736}
5737
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005738static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005739{
Eric Andersen25f27032001-04-26 23:22:31 +00005740 struct in_str input;
5741 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005742 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005743}
5744
Denis Vlasenkof9375282009-04-05 19:13:39 +00005745/* Called a few times only (or even once if "sh -c") */
5746static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00005747{
Denis Vlasenkof9375282009-04-05 19:13:39 +00005748 unsigned sig;
5749 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005750
Denis Vlasenkof9375282009-04-05 19:13:39 +00005751 mask = (1 << SIGQUIT);
5752 if (G_interactive_fd) {
5753 mask = 0
5754 | (1 << SIGQUIT)
5755 | (1 << SIGTERM)
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005756//TODO | (1 << SIGHUP)
Denis Vlasenkof9375282009-04-05 19:13:39 +00005757#if ENABLE_HUSH_JOB
5758 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5759#endif
5760 | (1 << SIGINT)
5761 ;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005762 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005763 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00005764
Denis Vlasenkof9375282009-04-05 19:13:39 +00005765 if (!second_time)
5766 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5767 sig = 0;
5768 while (mask) {
5769 if (mask & 1)
5770 sigaddset(&G.blocked_set, sig);
5771 mask >>= 1;
5772 sig++;
5773 }
5774 sigdelset(&G.blocked_set, SIGCHLD);
5775
5776 sigprocmask(SIG_SETMASK, &G.blocked_set,
5777 second_time ? NULL : &G.inherited_set);
5778 /* POSIX allows shell to re-enable SIGCHLD
5779 * even if it was SIG_IGN on entry */
5780// G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5781 if (!second_time)
5782 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5783}
5784
5785#if ENABLE_HUSH_JOB
5786/* helper */
5787static void maybe_set_to_sigexit(int sig)
5788{
5789 void (*handler)(int);
5790 /* non_DFL_mask'ed signals are, well, masked,
5791 * no need to set handler for them.
5792 */
5793 if (!((G.non_DFL_mask >> sig) & 1)) {
5794 handler = signal(sig, sigexit);
5795 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5796 signal(sig, handler);
5797 }
5798}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005799/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005800static void set_fatal_handlers(void)
5801{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00005802 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005803 if (HUSH_DEBUG) {
5804 maybe_set_to_sigexit(SIGILL );
5805 maybe_set_to_sigexit(SIGFPE );
5806 maybe_set_to_sigexit(SIGBUS );
5807 maybe_set_to_sigexit(SIGSEGV);
5808 maybe_set_to_sigexit(SIGTRAP);
5809 } /* else: hush is perfect. what SEGV? */
5810 maybe_set_to_sigexit(SIGABRT);
5811 /* bash 3.2 seems to handle these just like 'fatal' ones */
5812 maybe_set_to_sigexit(SIGPIPE);
5813 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005814//TODO: disable and move down when proper SIGHUP handling is added
Denis Vlasenkof9375282009-04-05 19:13:39 +00005815 maybe_set_to_sigexit(SIGHUP );
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005816 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00005817 * if we aren't interactive... but in this case
5818 * we never want to restore pgrp on exit, and this fn is not called */
5819 /*maybe_set_to_sigexit(SIGTERM);*/
5820 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00005821}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005822#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00005823
Denis Vlasenkod5762932009-03-31 11:22:57 +00005824static int set_mode(const char cstate, const char mode)
5825{
5826 int state = (cstate == '-' ? 1 : 0);
5827 switch (mode) {
5828 case 'n': G.fake_mode = state; break;
5829 case 'x': /*G.debug_mode = state;*/ break;
5830 default: return EXIT_FAILURE;
5831 }
5832 return EXIT_SUCCESS;
5833}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005834
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00005835int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00005836int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00005837{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005838 static const struct variable const_shell_ver = {
5839 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005840 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005841 .max_len = 1, /* 0 can provoke free(name) */
5842 .flg_export = 1,
5843 .flg_read_only = 1,
5844 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00005845 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005846 int opt;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005847 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005848 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00005849
Denis Vlasenko574f2f42008-02-27 18:41:59 +00005850 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005851 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005852 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005853#if !BB_MMU
5854 G.argv0_for_re_execing = argv[0];
5855#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005856 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005857 G.shell_ver = const_shell_ver; /* copying struct here */
5858 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005859 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005860 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5861 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005862 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005863 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005864 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005865 if (e) while (*e) {
5866 char *value = strchr(*e, '=');
5867 if (value) { /* paranoia */
5868 cur_var->next = xzalloc(sizeof(*cur_var));
5869 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00005870 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005871 cur_var->max_len = strlen(*e);
5872 cur_var->flg_export = 1;
5873 }
5874 e++;
5875 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005876 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005877 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenko38f63192007-01-22 09:03:07 +00005878#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00005879 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00005880#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00005881 G.global_argc = argc;
5882 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00005883 /* Initialize some more globals to non-zero values */
5884 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005885#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00005886 if (ENABLE_FEATURE_EDITING)
5887 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005888 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005889#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00005890
Denis Vlasenkoed782372009-04-10 00:45:02 +00005891 if (setjmp(die_jmp)) {
5892 /* xfunc has failed! die die die */
5893 /* no EXIT traps, this is an escape hatch! */
5894 G.exiting = 1;
5895 hush_exit(xfunc_error_retval);
5896 }
5897
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005898 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005899 * block_signals(0) if we are going to execute "sh <script>",
5900 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005901 * If we later decide that we are interactive, we run block_signals(0)
5902 * (or re-run block_signals(1) if we ran block_signals(0) before)
5903 * in order to intercept (more) signals.
5904 */
5905
5906 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005907 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005908 while (1) {
5909 opt = getopt(argc, argv, "c:xins"
5910#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00005911 "<:$:R:V:"
5912# if ENABLE_HUSH_FUNCTIONS
5913 "F:"
5914# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005915#endif
5916 );
5917 if (opt <= 0)
5918 break;
Eric Andersen25f27032001-04-26 23:22:31 +00005919 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005920 case 'c':
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005921 if (!G.root_pid)
5922 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005923 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00005924 if (!argv[optind]) {
5925 /* -c 'script' (no params): prevent empty $0 */
5926 *--G.global_argv = argv[0];
5927 optind--;
5928 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005929 G.global_argc = argc - optind;
Denis Vlasenkof9375282009-04-05 19:13:39 +00005930 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005931 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005932 goto final_return;
5933 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00005934 /* Well, we cannot just declare interactiveness,
5935 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005936 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005937 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005938 case 's':
5939 /* "-s" means "read from stdin", but this is how we always
5940 * operate, so simply do nothing here. */
5941 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005942#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00005943 case '<': /* "big heredoc" support */
5944 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5945 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005946 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005947 G.root_pid = bb_strtou(optarg, &optarg, 16);
5948 optarg++;
5949 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5950 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005951 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005952# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005953 optarg++;
5954 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005955# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005956 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005957 case 'R':
5958 case 'V':
5959 set_local_var(xstrdup(optarg), 0, opt == 'R');
5960 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00005961# if ENABLE_HUSH_FUNCTIONS
5962 case 'F': {
5963 struct function *funcp = new_function(optarg);
5964 /* funcp->name is already set to optarg */
5965 /* funcp->body is set to NULL. It's a special case. */
5966 funcp->body_as_string = argv[optind];
5967 optind++;
5968 break;
5969 }
5970# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005971#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005972 case 'n':
5973 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00005974 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005975 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005976 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005977#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005978 fprintf(stderr, "Usage: sh [FILE]...\n"
5979 " or: sh -c command [args]...\n\n");
5980 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005981#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005982 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005983#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005984 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005985 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005986
5987 if (!G.root_pid)
5988 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00005989
5990 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005991 if (argv[0] && argv[0][0] == '-') {
5992 FILE *input;
5993 /* XXX what should argv be while sourcing /etc/profile? */
5994 debug_printf("sourcing /etc/profile\n");
5995 input = fopen_for_read("/etc/profile");
5996 if (input != NULL) {
5997 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00005998 block_signals(0); /* 0: called 1st time */
5999 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006000 parse_and_run_file(input);
6001 fclose(input);
6002 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006003 /* bash: after sourcing /etc/profile,
6004 * tries to source (in the given order):
6005 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6006 * stopping of first found. --noprofile turns this off.
6007 * bash also sources ~/.bash_logout on exit.
6008 * If called as sh, skips .bash_XXX files.
6009 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006010 }
6011
Denis Vlasenkof9375282009-04-05 19:13:39 +00006012 if (argv[optind]) {
6013 FILE *input;
6014 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006015 * "bash <script>" (which is never interactive (unless -i?))
6016 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006017 * If called as sh, does the same but with $ENV.
6018 */
6019 debug_printf("running script '%s'\n", argv[optind]);
6020 G.global_argv = argv + optind;
6021 G.global_argc = argc - optind;
6022 input = xfopen_for_read(argv[optind]);
6023 close_on_exec_on(fileno(input));
6024 if (!signal_mask_is_inited)
6025 block_signals(0); /* 0: called 1st time */
6026 parse_and_run_file(input);
6027#if ENABLE_FEATURE_CLEAN_UP
6028 fclose(input);
6029#endif
6030 goto final_return;
6031 }
6032
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006033 /* Up to here, shell was non-interactive. Now it may become one.
6034 * NB: don't forget to (re)run block_signals(0/1) as needed.
6035 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006036
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006037 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00006038 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006039 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006040 * no arguments remaining or the -s flag given
6041 * standard input is a terminal
6042 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006043 * Refer to Posix.2, the description of the 'sh' utility.
6044 */
6045#if ENABLE_HUSH_JOB
6046 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006047 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
Denis Vlasenkof9375282009-04-05 19:13:39 +00006048 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006049//TODO: "interactive" and "have job control" are two different things.
6050//If tcgetpgrp fails here, "have job control" is false, but "interactive"
6051//should stay on! Currently, we mix these into one.
Denis Vlasenko87a86552008-07-29 19:43:10 +00006052 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006053 /* try to dup stdin to high fd#, >= 255 */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006054 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6055 if (G_interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006056 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006057 G_interactive_fd = dup(STDIN_FILENO);
6058 if (G_interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006059 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006060 G_interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006061 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006062// TODO: track & disallow any attempts of user
6063// to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006064 }
Eric Andersen25f27032001-04-26 23:22:31 +00006065 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006066 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006067 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006068 pid_t shell_pgrp;
6069
6070 /* We are indeed interactive shell, and we will perform
6071 * job control. Setting up for that. */
6072
6073 close_on_exec_on(G_interactive_fd);
6074 /* If we were run as 'hush &', sleep until we are
6075 * in the foreground (tty pgrp == our pgrp).
6076 * If we get started under a job aware app (like bash),
6077 * make sure we are now in charge so we don't fight over
6078 * who gets the foreground */
6079 while (1) {
6080 shell_pgrp = getpgrp();
6081 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6082 if (G.saved_tty_pgrp == shell_pgrp)
6083 break;
6084 /* send TTIN to ourself (should stop us) */
6085 kill(- shell_pgrp, SIGTTIN);
6086 }
6087 /* Block some signals */
6088 block_signals(signal_mask_is_inited);
6089 /* Set other signals to restore saved_tty_pgrp */
6090 set_fatal_handlers();
6091 /* Put ourselves in our own process group */
6092 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6093 /* Grab control of the terminal */
6094 tcsetpgrp(G_interactive_fd, getpid());
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006095 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006096 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006097 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006098 } else if (!signal_mask_is_inited) {
6099 block_signals(0); /* 0: called 1st time */
6100 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006101#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006102 /* No job control compiled in, only prompt/line editing */
6103 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006104 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6105 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006106 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006107 G_interactive_fd = dup(STDIN_FILENO);
6108 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006109 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006110 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006111 }
6112 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006113 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006114 close_on_exec_on(G_interactive_fd);
6115 block_signals(signal_mask_is_inited);
6116 } else if (!signal_mask_is_inited) {
6117 block_signals(0);
6118 }
6119#else
6120 /* We have interactiveness code disabled */
6121 if (!signal_mask_is_inited) {
6122 block_signals(0);
6123 }
6124#endif
6125 /* bash:
6126 * if interactive but not a login shell, sources ~/.bashrc
6127 * (--norc turns this off, --rcfile <file> overrides)
6128 */
6129
6130 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006131 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysingerb2705e12009-03-23 08:44:02 +00006132 printf("Enter 'help' for a list of built-in commands.\n\n");
6133 }
6134
Denis Vlasenkof9375282009-04-05 19:13:39 +00006135 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006136
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006137 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006138#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006139 if (G.cwd != bb_msg_unknown)
6140 free((char*)G.cwd);
6141 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006142 while (cur_var) {
6143 struct variable *tmp = cur_var;
6144 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006145 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006146 cur_var = cur_var->next;
6147 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006148 }
Eric Andersen25f27032001-04-26 23:22:31 +00006149#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006150 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006151}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006152
6153
6154#if ENABLE_LASH
6155int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6156int lash_main(int argc, char **argv)
6157{
6158 //bb_error_msg("lash is deprecated, please use hush instead");
6159 return hush_main(argc, argv);
6160}
6161#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006162
6163
6164/*
6165 * Built-ins
6166 */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006167static int builtin_trap(char **argv)
6168{
Denis Vlasenkod5762932009-03-31 11:22:57 +00006169 int i;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006170 int sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006171 char *new_cmd;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006172
6173 if (!G.traps)
Denis Vlasenkod5762932009-03-31 11:22:57 +00006174 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006175
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006176 argv++;
6177 if (!*argv) {
6178 /* No args: print all trapped. This isn't 100% correct as we
6179 * should be escaping the cmd so that it can be pasted back in
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006180 */
6181 for (i = 0; i < NSIG; ++i)
Denis Vlasenkod5762932009-03-31 11:22:57 +00006182 if (G.traps[i])
6183 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006184 return EXIT_SUCCESS;
6185 }
6186
Denis Vlasenkod5762932009-03-31 11:22:57 +00006187 new_cmd = NULL;
6188 i = 0;
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006189 /* If first arg is decimal: reset all specified signals */
6190 sig = bb_strtou(*argv, NULL, 10);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006191 if (errno == 0) {
6192 int ret;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006193 set_all:
6194 ret = EXIT_SUCCESS;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006195 while (*argv) {
6196 sig = get_signum(*argv++);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006197 if (sig < 0 || sig >= NSIG) {
6198 ret = EXIT_FAILURE;
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006199 /* Mimic bash message exactly */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006200 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
6201 continue;
6202 }
6203
Denis Vlasenkod5762932009-03-31 11:22:57 +00006204 free(G.traps[sig]);
6205 G.traps[sig] = xstrdup(new_cmd);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006206
Denis Vlasenkod5762932009-03-31 11:22:57 +00006207 debug_printf("trap: setting SIG%s (%i) to '%s'",
6208 get_signame(sig), sig, G.traps[sig]);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006209
6210 /* There is no signal for 0 (EXIT) */
6211 if (sig == 0)
6212 continue;
6213
6214 if (new_cmd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006215 sigaddset(&G.blocked_set, sig);
6216 } else {
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006217 /* There was a trap handler, we are removing it
Denis Vlasenkod5762932009-03-31 11:22:57 +00006218 * (if sig has non-DFL handling,
6219 * we don't need to do anything) */
6220 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6221 continue;
6222 sigdelset(&G.blocked_set, sig);
6223 }
6224 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006225 }
6226 return ret;
6227 }
6228
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006229 /* First arg is "-": reset all specified to default */
6230 /* First arg is "": ignore all specified */
6231 /* Everything else: execute first arg upon signal */
Denis Vlasenkod5762932009-03-31 11:22:57 +00006232 if (!argv[1]) {
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006233 bb_error_msg("trap: invalid arguments");
6234 return EXIT_FAILURE;
6235 }
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006236 if (NOT_LONE_DASH(*argv))
Denis Vlasenkod5762932009-03-31 11:22:57 +00006237 new_cmd = *argv;
6238 argv++;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006239 goto set_all;
6240}
6241
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006242static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006243{
6244 return 0;
6245}
6246
6247static int builtin_test(char **argv)
6248{
6249 int argc = 0;
6250 while (*argv) {
6251 argc++;
6252 argv++;
6253 }
6254 return test_main(argc, argv - argc);
6255}
6256
6257static int builtin_echo(char **argv)
6258{
6259 int argc = 0;
6260 while (*argv) {
6261 argc++;
6262 argv++;
6263 }
6264 return echo_main(argc, argv - argc);
6265}
6266
6267static int builtin_eval(char **argv)
6268{
6269 int rcode = EXIT_SUCCESS;
6270
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006271 if (*++argv) {
6272 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006273 /* bash:
6274 * eval "echo Hi; done" ("done" is syntax error):
6275 * "echo Hi" will not execute too.
6276 */
6277 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006278 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006279 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006280 }
6281 return rcode;
6282}
6283
6284static int builtin_cd(char **argv)
6285{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006286 const char *newdir = argv[1];
6287 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006288 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006289 * bash says "bash: cd: HOME not set" and does nothing
6290 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006291 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006292 newdir = getenv("HOME") ? : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006293 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006294 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006295 /* Mimic bash message exactly */
6296 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006297 return EXIT_FAILURE;
6298 }
6299 set_cwd();
6300 return EXIT_SUCCESS;
6301}
6302
6303static int builtin_exec(char **argv)
6304{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006305 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006306 return EXIT_SUCCESS; /* bash does this */
6307 {
6308#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006309 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006310#endif
6311// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006312 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006313 /* never returns */
6314 }
6315}
6316
6317static int builtin_exit(char **argv)
6318{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006319 debug_printf_exec("%s()\n", __func__);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006320// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
6321 //puts("exit"); /* bash does it */
6322// TODO: warn if we have background jobs: "There are stopped jobs"
6323// On second consecutive 'exit', exit anyway.
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006324// perhaps use G.exiting = -1 as indicator "last cmd was exit"
6325
6326 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006327 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006328 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006329 /* mimic bash: exit 123abc == exit 255 + error msg */
6330 xfunc_error_retval = 255;
6331 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006332 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006333}
6334
6335static int builtin_export(char **argv)
6336{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006337 if (*++argv == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006338 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006339 if (e) {
6340 while (*e) {
6341#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006342 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006343#else
6344 /* ash emits: export VAR='VAL'
6345 * bash: declare -x VAR="VAL"
6346 * we follow ash example */
6347 const char *s = *e++;
6348 const char *p = strchr(s, '=');
6349
6350 if (!p) /* wtf? take next variable */
6351 continue;
6352 /* export var= */
6353 printf("export %.*s", (int)(p - s) + 1, s);
6354 s = p + 1;
6355 while (*s) {
6356 if (*s != '\'') {
6357 p = strchrnul(s, '\'');
6358 /* print 'xxxx' */
6359 printf("'%.*s'", (int)(p - s), s);
6360 if (*p == '\0')
6361 break;
6362 s = p;
6363 }
6364 /* s points to '; print ''...'''" */
6365 putchar('"');
6366 do putchar('\''); while (*++s == '\'');
6367 putchar('"');
6368 }
6369 putchar('\n');
6370#endif
6371 }
6372 fflush(stdout);
6373 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006374 return EXIT_SUCCESS;
6375 }
6376
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006377 do {
6378 const char *value;
6379 char *name = *argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006380
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006381 value = strchr(name, '=');
6382 if (!value) {
6383 /* They are exporting something without a =VALUE */
6384 struct variable *var;
6385
6386 var = get_local_var(name);
6387 if (var) {
6388 var->flg_export = 1;
6389 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6390 putenv(var->varstr);
6391 }
6392 /* bash does not return an error when trying to export
6393 * an undefined variable. Do likewise. */
6394 continue;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006395 }
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006396 set_local_var(xstrdup(name), 1, 0);
6397 } while (*++argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006398
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006399 return EXIT_SUCCESS;
6400}
6401
6402#if ENABLE_HUSH_JOB
6403/* built-in 'fg' and 'bg' handler */
6404static int builtin_fg_bg(char **argv)
6405{
6406 int i, jobnum;
6407 struct pipe *pi;
6408
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006409 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006410 return EXIT_FAILURE;
6411 /* If they gave us no args, assume they want the last backgrounded task */
6412 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006413 for (pi = G.job_list; pi; pi = pi->next) {
6414 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006415 goto found;
6416 }
6417 }
6418 bb_error_msg("%s: no current job", argv[0]);
6419 return EXIT_FAILURE;
6420 }
6421 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6422 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6423 return EXIT_FAILURE;
6424 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006425 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006426 if (pi->jobid == jobnum) {
6427 goto found;
6428 }
6429 }
6430 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6431 return EXIT_FAILURE;
6432 found:
6433 // TODO: bash prints a string representation
6434 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006435 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006436 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006437 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006438 }
6439
6440 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006441 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6442 for (i = 0; i < pi->num_cmds; i++) {
6443 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6444 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006445 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006446 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006447
6448 i = kill(- pi->pgrp, SIGCONT);
6449 if (i < 0) {
6450 if (errno == ESRCH) {
6451 delete_finished_bg_job(pi);
6452 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006453 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006454 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006455 }
6456
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006457 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006458 remove_bg_job(pi);
6459 return checkjobs_and_fg_shell(pi);
6460 }
6461 return EXIT_SUCCESS;
6462}
6463#endif
6464
6465#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006466static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006467{
6468 const struct built_in_command *x;
6469
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006470 printf("\n"
6471 "Built-in commands:\n"
6472 "------------------\n");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006473 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6474 printf("%s\t%s\n", x->cmd, x->descr);
6475 }
6476 printf("\n\n");
6477 return EXIT_SUCCESS;
6478}
6479#endif
6480
6481#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006482static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006483{
6484 struct pipe *job;
6485 const char *status_string;
6486
Denis Vlasenko87a86552008-07-29 19:43:10 +00006487 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006488 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006489 status_string = "Stopped";
6490 else
6491 status_string = "Running";
6492
6493 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6494 }
6495 return EXIT_SUCCESS;
6496}
6497#endif
6498
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00006499#if HUSH_DEBUG
6500static int builtin_memleak(char **argv UNUSED_PARAM)
6501{
6502 void *p;
6503 unsigned long l;
6504
6505 /* Crude attempt to find where "free memory" starts,
6506 * sans fragmentation. */
6507 p = malloc(240);
6508 l = (unsigned long)p;
6509 free(p);
6510 p = malloc(3400);
6511 if (l < (unsigned long)p) l = (unsigned long)p;
6512 free(p);
6513
6514 if (!G.memleak_value)
6515 G.memleak_value = l;
6516
6517 l -= G.memleak_value;
6518 if ((long)l < 0)
6519 l = 0;
6520 l /= 1024;
6521 if (l > 127)
6522 l = 127;
6523
6524 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6525 return l;
6526}
6527#endif
6528
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006529static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006530{
6531 puts(set_cwd());
6532 return EXIT_SUCCESS;
6533}
6534
6535static int builtin_read(char **argv)
6536{
6537 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006538 const char *name = "REPLY";
6539
6540 if (argv[1]) {
6541 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006542 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6543 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006544 if (!is_well_formed_var_name(name, '\0')) {
6545 /* Mimic bash message */
6546 bb_error_msg("read: '%s': not a valid identifier", name);
6547 return 1;
6548 }
6549 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006550
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006551//TODO: bash unbackslashes input, splits words and puts them in argv[i]
6552
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006553 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006554 return set_local_var(string, 0, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006555}
6556
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006557/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6558 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006559 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006560 * set [-abCefhmnuvx] [-o option] [argument...]
6561 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006562 * set -- [argument...]
6563 * set -o
6564 * set +o
6565 * Implementations shall support the options in both their hyphen and
6566 * plus-sign forms. These options can also be specified as options to sh.
6567 * Examples:
6568 * Write out all variables and their values: set
6569 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6570 * Turn on the -x and -v options: set -xv
6571 * Unset all positional parameters: set --
6572 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6573 * Set the positional parameters to the expansion of x, even if x expands
6574 * with a leading '-' or '+': set -- $x
6575 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006576 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006577 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006578static int builtin_set(char **argv)
6579{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006580 int n;
6581 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006582 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006583
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006584 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006585 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00006586 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006587 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006588 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006589 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006590
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006591 do {
6592 if (!strcmp(arg, "--")) {
6593 ++argv;
6594 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006595 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00006596 if (arg[0] != '+' && arg[0] != '-')
6597 break;
6598 for (n = 1; arg[n]; ++n)
6599 if (set_mode(arg[0], arg[n]))
6600 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006601 } while ((arg = *++argv) != NULL);
6602 /* Now argv[0] is 1st argument */
6603
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006604 if (arg == NULL)
6605 return EXIT_SUCCESS;
6606 set_argv:
6607
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006608 /* NB: G.global_argv[0] ($0) is never freed/changed */
6609 g_argv = G.global_argv;
6610 if (G.global_args_malloced) {
6611 pp = g_argv;
6612 while (*++pp)
6613 free(*pp);
6614 g_argv[1] = NULL;
6615 } else {
6616 G.global_args_malloced = 1;
6617 pp = xzalloc(sizeof(pp[0]) * 2);
6618 pp[0] = g_argv[0]; /* retain $0 */
6619 g_argv = pp;
6620 }
6621 /* This realloc's G.global_argv */
6622 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6623
6624 n = 1;
6625 while (*++pp)
6626 n++;
6627 G.global_argc = n;
6628
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006629 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006630
6631 /* Nothing known, so abort */
6632 error:
6633 bb_error_msg("set: %s: invalid option", arg);
6634 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006635}
6636
6637static int builtin_shift(char **argv)
6638{
6639 int n = 1;
6640 if (argv[1]) {
6641 n = atoi(argv[1]);
6642 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006643 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006644 if (G.global_args_malloced) {
6645 int m = 1;
6646 while (m <= n)
6647 free(G.global_argv[m++]);
6648 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006649 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006650 memmove(&G.global_argv[1], &G.global_argv[n+1],
6651 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006652 return EXIT_SUCCESS;
6653 }
6654 return EXIT_FAILURE;
6655}
6656
6657static int builtin_source(char **argv)
6658{
6659 FILE *input;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006660
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006661 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006662 return EXIT_FAILURE;
6663
6664 /* XXX search through $PATH is missing */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006665 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006666 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006667 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006668 return EXIT_FAILURE;
6669 }
6670 close_on_exec_on(fileno(input));
6671
6672 /* Now run the file */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006673//TODO:
Denis Vlasenko87a86552008-07-29 19:43:10 +00006674 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006675 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00006676 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006677 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006678 fclose(input);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006679 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006680}
6681
6682static int builtin_umask(char **argv)
6683{
6684 mode_t new_umask;
6685 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006686 if (arg) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006687//TODO: umask may take chmod-like symbolic masks
Mike Frysinger40b8dc42009-03-29 00:50:30 +00006688 new_umask = bb_strtou(arg, NULL, 8);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006689 if (errno) {
6690 //Message? bash examples:
6691 //bash: umask: 'q': invalid symbolic mode operator
6692 //bash: umask: 999: octal number out of range
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006693 return EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006694 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006695 } else {
6696 new_umask = umask(0);
6697 printf("%.3o\n", (unsigned) new_umask);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006698 /* fall through and restore new_umask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006699 }
6700 umask(new_umask);
6701 return EXIT_SUCCESS;
6702}
6703
Mike Frysingerd690f682009-03-30 06:50:54 +00006704/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006705static int builtin_unset(char **argv)
6706{
Mike Frysingerd690f682009-03-30 06:50:54 +00006707 int ret;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006708 char var;
Mike Frysingerd690f682009-03-30 06:50:54 +00006709
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006710 if (!*++argv)
Mike Frysingerd690f682009-03-30 06:50:54 +00006711 return EXIT_SUCCESS;
6712
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006713 var = 'v';
6714 if (argv[0][0] == '-') {
6715 switch (argv[0][1]) {
6716 case 'v':
6717 case 'f':
6718 var = argv[0][1];
6719 break;
Mike Frysingerd690f682009-03-30 06:50:54 +00006720 default:
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006721 bb_error_msg("unset: %s: invalid option", *argv);
Mike Frysingerd690f682009-03-30 06:50:54 +00006722 return EXIT_FAILURE;
6723 }
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006724//TODO: disallow "unset -vf ..." too
6725 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006726 }
6727
6728 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006729 while (*argv) {
6730 if (var == 'v') {
6731 if (unset_local_var(*argv)) {
6732 /* unset <nonexistent_var> doesn't fail.
6733 * Error is when one tries to unset RO var.
6734 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00006735 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006736 }
Mike Frysingerd690f682009-03-30 06:50:54 +00006737 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006738//#if ENABLE_HUSH_FUNCTIONS
6739// else {
6740// unset_local_func(*argv);
6741// }
6742//#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006743 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006744 }
6745 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006746}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006747
Mike Frysinger56bdea12009-03-28 20:01:58 +00006748/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6749static int builtin_wait(char **argv)
6750{
6751 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006752 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006753
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006754 if (*++argv == NULL) {
6755 /* Don't care about wait results */
6756 /* Note 1: must wait until there are no more children */
6757 /* Note 2: must be interruptible */
6758 /* Examples:
6759 * $ sleep 3 & sleep 6 & wait
6760 * [1] 30934 sleep 3
6761 * [2] 30935 sleep 6
6762 * [1] Done sleep 3
6763 * [2] Done sleep 6
6764 * $ sleep 3 & sleep 6 & wait
6765 * [1] 30936 sleep 3
6766 * [2] 30937 sleep 6
6767 * [1] Done sleep 3
6768 * ^C <-- after ~4 sec from keyboard
6769 * $
6770 */
6771 sigaddset(&G.blocked_set, SIGCHLD);
6772 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6773 while (1) {
6774 checkjobs(NULL);
6775 if (errno == ECHILD)
6776 break;
6777 /* Wait for SIGCHLD or any other signal of interest */
6778 /* sigtimedwait with infinite timeout: */
6779 sig = sigwaitinfo(&G.blocked_set, NULL);
6780 if (sig > 0) {
6781 sig = check_and_run_traps(sig);
6782 if (sig && sig != SIGCHLD) { /* see note 2 */
6783 ret = 128 + sig;
6784 break;
6785 }
6786 }
6787 }
6788 sigdelset(&G.blocked_set, SIGCHLD);
6789 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6790 return ret;
6791 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00006792
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006793 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00006794 while (*argv) {
6795 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00006796 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006797 /* mimic bash message */
6798 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00006799 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006800 }
6801 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00006802 if (WIFSIGNALED(status))
6803 ret = 128 + WTERMSIG(status);
6804 else if (WIFEXITED(status))
6805 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00006806 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00006807 ret = EXIT_FAILURE;
6808 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006809 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00006810 ret = 127;
6811 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00006812 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006813 }
6814
6815 return ret;
6816}
6817
Denis Vlasenkodadfb492008-07-29 10:16:05 +00006818#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006819static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006820{
Denis Vlasenko87a86552008-07-29 19:43:10 +00006821 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006822 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00006823 return EXIT_SUCCESS; /* bash compat */
6824 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006825 G.flag_break_continue++; /* BC_BREAK = 1 */
6826 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006827 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006828 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6829 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006830 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00006831 G.flag_break_continue = BC_BREAK;
6832 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006833 }
6834 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006835 if (G.depth_of_loop < G.depth_break_continue)
6836 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006837 return EXIT_SUCCESS;
6838}
6839
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006840static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006841{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006842 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6843 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006844}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00006845#endif