blob: 61b6a79251ef9da02e61adebf08fbd84e9aca6ff [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 Vlasenkofa4ca782009-04-16 12:00:15 +000054 * $var refs in function do not pick up values set by "var=val func"
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000055 * builtins: return, ulimit
Eric Andersen25f27032001-04-26 23:22:31 +000056 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000057 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000058 * continuation lines, both explicit and implicit - done?
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000059 * SIGHUP handling
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000060 * 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
Denis Vlasenko1943aec2009-04-09 14:15:57 +000086
87
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000088#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +000089# undef BB_MMU
90# undef USE_FOR_NOMMU
91# undef USE_FOR_MMU
92# define BB_MMU 0
93# define USE_FOR_NOMMU(...) __VA_ARGS__
94# define USE_FOR_MMU(...)
95#endif
96
Denis Vlasenko61befda2008-11-25 01:36:03 +000097#if defined SINGLE_APPLET_MAIN
98/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000099# undef CONFIG_FEATURE_SH_STANDALONE
100# undef ENABLE_FEATURE_SH_STANDALONE
101# undef USE_FEATURE_SH_STANDALONE
102# define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
103# define ENABLE_FEATURE_SH_STANDALONE 0
104# define USE_FEATURE_SH_STANDALONE(...)
105# define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000106#endif
107
Denis Vlasenko05743d72008-02-10 12:10:08 +0000108#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000109# undef ENABLE_FEATURE_EDITING
110# define ENABLE_FEATURE_EDITING 0
111# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
112# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000113#endif
114
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000115/* Do we support ANY keywords? */
116#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000117# define HAS_KEYWORDS 1
118# define IF_HAS_KEYWORDS(...) __VA_ARGS__
119# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000120#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000121# define HAS_KEYWORDS 0
122# define IF_HAS_KEYWORDS(...)
123# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000124#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000125
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000126/* If you comment out one of these below, it will be #defined later
127 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000128#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000129/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000130#define debug_printf_parse(...) do {} while (0)
131#define debug_print_tree(a, b) do {} while (0)
132#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000133#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000134#define debug_printf_jobs(...) do {} while (0)
135#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000136#define debug_printf_glob(...) do {} while (0)
137#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000138#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000139#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000140
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000141#define ERR_PTR ((void*)(long)1)
142
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000143#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000144
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000145#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000146
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000147static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
148
149/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000150 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000151 */
152#if !BB_MMU
153typedef struct nommu_save_t {
154 char **new_env;
155 char **old_env;
156 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000157 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000158} nommu_save_t;
159#endif
160
Denis Vlasenko55789c62008-06-18 16:30:42 +0000161/* The descrip member of this structure is only used to make
162 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000163static const struct {
164 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000165 signed char default_fd;
166 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000167} redir_table[] = {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000168 { 0, 0, "??" },
Eric Andersen25f27032001-04-26 23:22:31 +0000169 { O_RDONLY, 0, "<" },
170 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
171 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000172 { O_RDONLY, 0, "<<" },
173 { O_CREAT|O_RDWR, 1, "<>" },
174/* Should not be needed. Bogus default_fd helps in debugging */
175/* { O_RDONLY, 77, "<<" }, */
Eric Andersen25f27032001-04-26 23:22:31 +0000176};
177
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000178typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000179 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000180#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000181 RES_IF ,
182 RES_THEN ,
183 RES_ELIF ,
184 RES_ELSE ,
185 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000186#endif
187#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000188 RES_FOR ,
189 RES_WHILE ,
190 RES_UNTIL ,
191 RES_DO ,
192 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000193#endif
194#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000195 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000196#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000197#if ENABLE_HUSH_CASE
198 RES_CASE ,
199 /* two pseudo-keywords support contrived "case" syntax: */
200 RES_MATCH , /* "word)" */
201 RES_CASEI , /* "this command is inside CASE" */
202 RES_ESAC ,
203#endif
204 RES_XXXX ,
205 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000206} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000207
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000208typedef struct o_string {
209 char *data;
210 int length; /* position where data is appended */
211 int maxlen;
212 /* Protect newly added chars against globbing
213 * (by prepending \ to *, ?, [, \) */
214 smallint o_escape;
215 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000216 /* At least some part of the string was inside '' or "",
217 * possibly empty one: word"", wo''rd etc. */
218 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000219 smallint has_empty_slot;
220 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
221} o_string;
222enum {
223 MAYBE_ASSIGNMENT = 0,
224 DEFINITELY_ASSIGNMENT = 1,
225 NOT_ASSIGNMENT = 2,
226 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
227};
228/* Used for initialization: o_string foo = NULL_O_STRING; */
229#define NULL_O_STRING { NULL }
230
231/* I can almost use ordinary FILE*. Is open_memstream() universally
232 * available? Where is it documented? */
233typedef struct in_str {
234 const char *p;
235 /* eof_flag=1: last char in ->p is really an EOF */
236 char eof_flag; /* meaningless if ->p == NULL */
237 char peek_buf[2];
238#if ENABLE_HUSH_INTERACTIVE
239 smallint promptme;
240 smallint promptmode; /* 0: PS1, 1: PS2 */
241#endif
242 FILE *file;
243 int (*get) (struct in_str *);
244 int (*peek) (struct in_str *);
245} in_str;
246#define i_getch(input) ((input)->get(input))
247#define i_peek(input) ((input)->peek(input))
248
Eric Andersen25f27032001-04-26 23:22:31 +0000249struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000250 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000251 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000252 int rd_fd; /* fd to redirect */
253 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
254 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000255 smallint rd_type; /* (enum redir_type) */
256 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000257 * and subsequently heredoc itself; and rd_dup is a bitmask:
258 * 1: do we need to trim leading tabs?
Denis Vlasenkoed055212009-04-11 10:37:10 +0000259 * 2: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000260 */
Eric Andersen25f27032001-04-26 23:22:31 +0000261};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000262typedef enum redir_type {
263 REDIRECT_INVALID = 0,
264 REDIRECT_INPUT = 1,
265 REDIRECT_OVERWRITE = 2,
266 REDIRECT_APPEND = 3,
267 REDIRECT_HEREDOC = 4,
268 REDIRECT_IO = 5,
269 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000270
271 REDIRFD_CLOSE = -3,
272 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000273 REDIRFD_TO_FILE = -1,
274 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000275
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000276 HEREDOC_SKIPTABS = 1,
277 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000278} redir_type;
279
Eric Andersen25f27032001-04-26 23:22:31 +0000280
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000281struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000282 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000283 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000284 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000285 smallint grp_type; /* GRP_xxx */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000286#define GRP_NORMAL 0
287#define GRP_SUBSHELL 1
288#if ENABLE_HUSH_FUNCTIONS
289# define GRP_FUNCTION 2
290#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000291 struct pipe *group; /* if non-NULL, this "command" is { list },
292 * ( list ), or a compound statement */
293#if !BB_MMU
294 char *group_as_string;
295#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000296#if ENABLE_HUSH_FUNCTIONS
297 struct function *child_func;
298/* This field is used to prevent a bug here:
299 * while...do f1() {a;}; f1; f1 {b;}; f1; done
300 * When we execute "f1() {a;}" cmd, we create new function and clear
301 * cmd->group, cmd->group_as_string, cmd->argv[0].
302 * when we execute "f1 {b;}", we notice that f1 exists,
303 * and that it's "parent cmd" struct is still "alive",
304 * we put those fields back into cmd->xxx
305 * (struct function has ->parent_cmd ptr to facilitate that).
306 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
307 * Without this trick, loop would execute a;b;b;b;...
308 * instead of correct sequence a;b;a;b;...
309 * When command is freed, it severs the link
310 * (sets ->child_func->parent_cmd to NULL).
311 */
312#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000313 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000314/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
315 * and on execution these are substituted with their values.
316 * Substitution can make _several_ words out of one argv[n]!
317 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000318 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000319 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000320 struct redir_struct *redirects; /* I/O redirections */
321};
Eric Andersen25f27032001-04-26 23:22:31 +0000322
323struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000324 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000325 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000326 int alive_cmds; /* number of commands running (not exited) */
327 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000328#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000329 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000330 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000331 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000332#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000333 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000334 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000335 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
336 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000337};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000338typedef enum pipe_style {
339 PIPE_SEQ = 1,
340 PIPE_AND = 2,
341 PIPE_OR = 3,
342 PIPE_BG = 4,
343} pipe_style;
Eric Andersen25f27032001-04-26 23:22:31 +0000344
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000345/* This holds pointers to the various results of parsing */
346struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000347 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000348 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000349 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000350 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000351 /* last command in pipe (being constructed right now) */
352 struct command *command;
353 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000354 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000355#if !BB_MMU
356 o_string as_string;
357#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000358#if HAS_KEYWORDS
359 smallint ctx_res_w;
360 smallint ctx_inverted; /* "! cmd | cmd" */
361#if ENABLE_HUSH_CASE
362 smallint ctx_dsemicolon; /* ";;" seen */
363#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000364 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
365 int old_flag;
366 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000367 * example: "if pipe1; pipe2; then pipe3; fi"
368 * when we see "if" or "then", we malloc and copy current context,
369 * and make ->stack point to it. then we parse pipeN.
370 * when closing "then" / fi" / whatever is found,
371 * we move list_head into ->stack->command->group,
372 * copy ->stack into current context, and delete ->stack.
373 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000374 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000375 struct parse_context *stack;
376#endif
377};
378
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000379/* On program start, environ points to initial environment.
380 * putenv adds new pointers into it, unsetenv removes them.
381 * Neither of these (de)allocates the strings.
382 * setenv allocates new strings in malloc space and does putenv,
383 * and thus setenv is unusable (leaky) for shell's purposes */
384#define setenv(...) setenv_is_leaky_dont_use()
385struct variable {
386 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000387 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000388 int max_len; /* if > 0, name is part of initial env; else name is malloced */
389 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000390 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000391};
392
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000393enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000394 BC_BREAK = 1,
395 BC_CONTINUE = 2,
396};
397
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000398#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000399struct function {
400 struct function *next;
401 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000402 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000403 struct pipe *body;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000404#if !BB_MMU
405 char *body_as_string;
406#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000407};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000408#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000409
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000410
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000411/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000412/* Sorted roughly by size (smaller offsets == smaller code) */
413struct globals {
414#if ENABLE_HUSH_INTERACTIVE
415 /* 'interactive_fd' is a fd# open to ctty, if we have one
416 * _AND_ if we decided to act interactively */
417 int interactive_fd;
418 const char *PS1;
419 const char *PS2;
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000420#define G_interactive_fd (G.interactive_fd)
421#else
422#define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000423#endif
424#if ENABLE_FEATURE_EDITING
425 line_input_t *line_input_state;
426#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000427 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000428 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000429#if ENABLE_HUSH_JOB
430 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000431 pid_t saved_tty_pgrp;
432 int last_jobid;
433 struct pipe *job_list;
434 struct pipe *toplevel_list;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000435#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000436 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000437#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000438 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000439#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000440 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000441 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000442 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000443 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000444 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000445 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000446 /* how many non-NULL argv's we have. NB: $# + 1 */
447 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000448 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000449#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000450 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000451#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000452#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000453 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000454 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000455#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000456 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000457 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000458 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000459 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000460#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000461 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000462#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000463 /* Signal and trap handling */
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000464// unsigned count_SIGCHLD;
465// unsigned handled_SIGCHLD;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000466 /* which signals have non-DFL handler (even with no traps set)? */
467 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000468 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000469 sigset_t blocked_set;
470 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000471#if HUSH_DEBUG
472 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000473 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000474#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000475 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000476};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000477#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000478/* Not #defining name to G.name - this quickly gets unwieldy
479 * (too many defines). Also, I actually prefer to see when a variable
480 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000481#define INIT_G() do { \
482 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
483} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000484
485
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000486/* Function prototypes for builtins */
487static int builtin_cd(char **argv);
488static int builtin_echo(char **argv);
489static int builtin_eval(char **argv);
490static int builtin_exec(char **argv);
491static int builtin_exit(char **argv);
492static int builtin_export(char **argv);
493#if ENABLE_HUSH_JOB
494static int builtin_fg_bg(char **argv);
495static int builtin_jobs(char **argv);
496#endif
497#if ENABLE_HUSH_HELP
498static int builtin_help(char **argv);
499#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000500#if HUSH_DEBUG
501static int builtin_memleak(char **argv);
502#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000503static int builtin_pwd(char **argv);
504static int builtin_read(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000505static int builtin_set(char **argv);
506static int builtin_shift(char **argv);
507static int builtin_source(char **argv);
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000508static int builtin_test(char **argv);
509static int builtin_trap(char **argv);
510static int builtin_true(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000511static int builtin_umask(char **argv);
512static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000513static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000514#if ENABLE_HUSH_LOOPS
515static int builtin_break(char **argv);
516static int builtin_continue(char **argv);
517#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000518
519/* Table of built-in functions. They can be forked or not, depending on
520 * context: within pipes, they fork. As simple commands, they do not.
521 * When used in non-forking context, they can change global variables
522 * in the parent shell process. If forked, of course they cannot.
523 * For example, 'unset foo | whatever' will parse and run, but foo will
524 * still be set at the end. */
525struct built_in_command {
526 const char *cmd;
527 int (*function)(char **argv);
528#if ENABLE_HUSH_HELP
529 const char *descr;
530#define BLTIN(cmd, func, help) { cmd, func, help }
531#else
532#define BLTIN(cmd, func, help) { cmd, func }
533#endif
534};
535
536/* For now, echo and test are unconditionally enabled.
537 * Maybe make it configurable? */
538static const struct built_in_command bltins[] = {
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000539 BLTIN("." , builtin_source , "Run commands in a file"),
540 BLTIN(":" , builtin_true , "No-op"),
541 BLTIN("[" , builtin_test , "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000542#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000543 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000544#endif
545#if ENABLE_HUSH_LOOPS
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000546 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000547#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000548 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000549#if ENABLE_HUSH_LOOPS
550 BLTIN("continue", builtin_continue, "Start new loop iteration"),
551#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000552 BLTIN("echo" , builtin_echo , "Write to stdout"),
553 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
554 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
555 BLTIN("exit" , builtin_exit , "Exit"),
556 BLTIN("export" , builtin_export , "Set environment variable"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000557#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000558 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000559#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000560#if ENABLE_HUSH_HELP
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000561 BLTIN("help" , builtin_help , "List shell built-in commands"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000562#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000563#if ENABLE_HUSH_JOB
564 BLTIN("jobs" , builtin_jobs , "List active jobs"),
565#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000566#if HUSH_DEBUG
567 BLTIN("memleak" , builtin_memleak , "Debug tool"),
568#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000569 BLTIN("pwd" , builtin_pwd , "Print current directory"),
570 BLTIN("read" , builtin_read , "Input environment variable"),
571// BLTIN("return" , builtin_return , "Return from a function"),
572 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
573 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
574 BLTIN("test" , builtin_test , "Test condition"),
575 BLTIN("trap" , builtin_trap , "Trap signals"),
576// BLTIN("ulimit" , builtin_return , "Control resource limits"),
577 BLTIN("umask" , builtin_umask , "Set file creation mask"),
578 BLTIN("unset" , builtin_unset , "Unset environment variable"),
579 BLTIN("wait" , builtin_wait , "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000580};
581
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000582
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000583/* Debug printouts.
584 */
585#if HUSH_DEBUG
586/* prevent disasters with G.debug_indent < 0 */
587# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
588# define debug_enter() (G.debug_indent++)
589# define debug_leave() (G.debug_indent--)
590#else
591# define indent() ((void)0)
592# define debug_enter() ((void)0)
593# define debug_leave() ((void)0)
594#endif
595
596#ifndef debug_printf
597# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
598#endif
599
600#ifndef debug_printf_parse
601# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
602#endif
603
604#ifndef debug_printf_exec
605#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
606#endif
607
608#ifndef debug_printf_env
609# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
610#endif
611
612#ifndef debug_printf_jobs
613# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
614# define DEBUG_JOBS 1
615#else
616# define DEBUG_JOBS 0
617#endif
618
619#ifndef debug_printf_expand
620# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
621# define DEBUG_EXPAND 1
622#else
623# define DEBUG_EXPAND 0
624#endif
625
626#ifndef debug_printf_glob
627# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
628# define DEBUG_GLOB 1
629#else
630# define DEBUG_GLOB 0
631#endif
632
633#ifndef debug_printf_list
634# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
635#endif
636
637#ifndef debug_printf_subst
638# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
639#endif
640
641#ifndef debug_printf_clean
642# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
643# define DEBUG_CLEAN 1
644#else
645# define DEBUG_CLEAN 0
646#endif
647
648#if DEBUG_EXPAND
649static void debug_print_strings(const char *prefix, char **vv)
650{
651 indent();
652 fprintf(stderr, "%s:\n", prefix);
653 while (*vv)
654 fprintf(stderr, " '%s'\n", *vv++);
655}
656#else
657#define debug_print_strings(prefix, vv) ((void)0)
658#endif
659
660
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000661/* Leak hunting. Use hush_leaktool.sh for post-processing.
662 */
663#if LEAK_HUNTING
664static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000665{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000666 void *ptr = xmalloc((size + 0xff) & ~0xff);
667 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
668 return ptr;
669}
670static void *xxrealloc(int lineno, void *ptr, size_t size)
671{
672 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
673 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
674 return ptr;
675}
676static char *xxstrdup(int lineno, const char *str)
677{
678 char *ptr = xstrdup(str);
679 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
680 return ptr;
681}
682static void xxfree(void *ptr)
683{
684 fdprintf(2, "free %p\n", ptr);
685 free(ptr);
686}
687#define xmalloc(s) xxmalloc(__LINE__, s)
688#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
689#define xstrdup(s) xxstrdup(__LINE__, s)
690#define free(p) xxfree(p)
691#endif
692
693
694/* Syntax and runtime errors. They always abort scripts.
695 * In interactive use they usually discard unparsed and/or unexecuted commands
696 * and return to the prompt.
697 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
698 */
699#if HUSH_DEBUG < 2
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000700# define die_if_script(lineno, fmt...) die_if_script(fmt)
701# define syntax_error(lineno, msg) syntax_error(msg)
702# define syntax_error_at(lineno, msg) syntax_error_at(msg)
703# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
704# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
705# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000706#endif
707
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000708static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000709{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000710 va_list p;
711
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000712#if HUSH_DEBUG >= 2
713 bb_error_msg("hush.c:%u", lineno);
714#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000715 va_start(p, fmt);
716 bb_verror_msg(fmt, p, NULL);
717 va_end(p);
718 if (!G_interactive_fd)
719 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000720}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000721
722static void syntax_error(unsigned lineno, const char *msg)
723{
724 if (msg)
725 die_if_script(lineno, "syntax error: %s", msg);
726 else
727 die_if_script(lineno, "syntax error", NULL);
728}
729
730static void syntax_error_at(unsigned lineno, const char *msg)
731{
732 die_if_script(lineno, "syntax error at '%s'", msg);
733}
734
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000735/* It so happens that all such cases are totally fatal
736 * even if shell is interactive: EOF while looking for closing
737 * delimiter. There is nowhere to read stuff from after that,
738 * it's EOF! The only choice is to terminate.
739 */
740static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000741static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000742{
743 char msg[2];
744 msg[0] = ch;
745 msg[1] = '\0';
746 die_if_script(lineno, "syntax error: unterminated %s", msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000747 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000748}
749
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000750static void syntax_error_unterm_str(unsigned lineno, const char *s)
751{
752 die_if_script(lineno, "syntax error: unterminated %s", s);
753}
754
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000755static void syntax_error_unexpected_ch(unsigned lineno, char ch)
756{
757 char msg[2];
758 msg[0] = ch;
759 msg[1] = '\0';
760 die_if_script(lineno, "syntax error: unexpected %s", msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000761}
762
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000763#if HUSH_DEBUG < 2
764# undef die_if_script
765# undef syntax_error
766# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000767# undef syntax_error_unterm_ch
768# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000769# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000770#else
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000771# define die_if_script(fmt...) die_if_script(__LINE__, fmt)
772# define syntax_error(msg) syntax_error(__LINE__, msg)
773# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
774# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
775# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
776# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000777#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000778
Denis Vlasenko552433b2009-04-04 19:29:21 +0000779
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000780/* Utility functions
781 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000782static int glob_needed(const char *s)
783{
784 while (*s) {
785 if (*s == '\\')
786 s++;
787 if (*s == '*' || *s == '[' || *s == '?')
788 return 1;
789 s++;
790 }
791 return 0;
792}
793
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000794static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000795{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000796 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000797 return 0;
798 s++;
799 while (isalnum(*s) || *s == '_')
800 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000801 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000802}
803
Denis Vlasenko55789c62008-06-18 16:30:42 +0000804/* Replace each \x with x in place, return ptr past NUL. */
805static char *unbackslash(char *src)
806{
807 char *dst = src;
808 while (1) {
809 if (*src == '\\')
810 src++;
811 if ((*dst++ = *src++) == '\0')
812 break;
813 }
814 return dst;
815}
816
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000817static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000818{
819 int i;
820 unsigned count1;
821 unsigned count2;
822 char **v;
823
824 v = strings;
825 count1 = 0;
826 if (v) {
827 while (*v) {
828 count1++;
829 v++;
830 }
831 }
832 count2 = 0;
833 v = add;
834 while (*v) {
835 count2++;
836 v++;
837 }
838 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
839 v[count1 + count2] = NULL;
840 i = count2;
841 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000842 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000843 return v;
844}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000845#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000846static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
847{
848 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
849 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
850 return ptr;
851}
852#define add_strings_to_strings(strings, add, need_to_dup) \
853 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
854#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000855
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000856static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000857{
858 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000859 v[0] = add;
860 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000861 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000862}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000863#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000864static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
865{
866 char **ptr = add_string_to_strings(strings, add);
867 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
868 return ptr;
869}
870#define add_string_to_strings(strings, add) \
871 xx_add_string_to_strings(__LINE__, strings, add)
872#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000873
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000874static void putenv_all(char **strings)
875{
876 if (!strings)
877 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000878 while (*strings) {
879 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000880 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000881 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000882}
883
884static char **putenv_all_and_save_old(char **strings)
885{
886 char **old = NULL;
887 char **s = strings;
888
889 if (!strings)
890 return old;
891 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000892 char *v, *eq;
893
894 eq = strchr(*strings, '=');
895 if (eq) {
896 *eq = '\0';
897 v = getenv(*strings);
898 *eq = '=';
899 if (v) {
900 /* v points to VAL in VAR=VAL, go back to VAR */
901 v -= (eq - *strings) + 1;
902 old = add_string_to_strings(old, v);
903 }
904 }
905 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000906 }
907 putenv_all(s);
908 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000909}
910
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000911static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000912{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000913 char **v;
914
915 if (!strings)
916 return;
917
918 v = strings;
919 while (*v) {
920 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000921 debug_printf_env("unsetenv '%s'\n", *v);
922 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000923 }
924 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000925 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000926 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000927}
928
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000929static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000930{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000931 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000932}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000933
934
Denis Vlasenkod5762932009-03-31 11:22:57 +0000935/* Basic theory of signal handling in shell
936 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000937 * This does not describe what hush does, rather, it is current understanding
938 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000939 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
940 *
941 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
942 * is finished or backgrounded. It is the same in interactive and
943 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000944 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000945 * ^C or ^Z from keyboard seem to execute "at once" because it usually
946 * backgrounds (i.e. stops) or kills all members of currently running
947 * pipe.
948 *
949 * Wait builtin in interruptible by signals for which user trap is set
950 * or by SIGINT in interactive shell.
951 *
952 * Trap handlers will execute even within trap handlers. (right?)
953 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000954 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000955 *
956 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000957 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000958 *
959 * Commands run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000960 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000961 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000962 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
963 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000964 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000965 * Siganls which differ from SIG_DFL action
966 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +0000967 *
968 * SIGQUIT: ignore
969 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000970 * SIGHUP (interactive):
971 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +0000972 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +0000973 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
974 * that all pipe members are stopped. Try this in bash:
975 * while :; do :; done - ^Z does not background it
976 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +0000977 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000978 * of the command line, show prompt. NB: ^C does not send SIGINT
979 * to interactive shell while shell is waiting for a pipe,
980 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000981 * Example 1: this waits 5 sec, but does not execute ls:
982 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
983 * Example 2: this does not wait and does not execute ls:
984 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
985 * Example 3: this does not wait 5 sec, but executes ls:
986 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +0000987 *
988 * (What happens to signals which are IGN on shell start?)
989 * (What happens with signal mask on shell start?)
990 *
991 * Implementation in hush
992 * ======================
993 * We use in-kernel pending signal mask to determine which signals were sent.
994 * We block all signals which we don't want to take action immediately,
995 * i.e. we block all signals which need to have special handling as described
996 * above, and all signals which have traps set.
997 * After each pipe execution, we extract any pending signals via sigtimedwait()
998 * and act on them.
999 *
1000 * unsigned non_DFL_mask: a mask of such "special" signals
1001 * sigset_t blocked_set: current blocked signal set
1002 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001003 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001004 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001005 * "trap 'cmd' SIGxxx":
1006 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001007 * after [v]fork, if we plan to be a shell:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001008 * nothing for {} child shell (say, "true | { true; true; } | true")
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001009 * unset all traps if () shell.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001010 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001011 * POSIX says pending signal mask is cleared in child - no need to clear it.
1012 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001013 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001014 * Note: as a result, we do not use signal handlers much. The only uses
1015 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
1016 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001017 */
1018
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001019//static void SIGCHLD_handler(int sig UNUSED_PARAM)
1020//{
1021// G.count_SIGCHLD++;
1022//}
1023
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001024static int check_and_run_traps(int sig)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001025{
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001026 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenkod5762932009-03-31 11:22:57 +00001027 smalluint save_rcode;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001028 int last_sig = 0;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001029
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001030 if (sig)
1031 goto jump_in;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001032 while (1) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001033 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
Denis Vlasenkod5762932009-03-31 11:22:57 +00001034 if (sig <= 0)
1035 break;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001036 jump_in:
1037 last_sig = sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001038 if (G.traps && G.traps[sig]) {
1039 if (G.traps[sig][0]) {
1040 /* We have user-defined handler */
1041 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001042 save_rcode = G.last_exitcode;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001043 builtin_eval(argv);
1044 free(argv[1]);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001045 G.last_exitcode = save_rcode;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001046 } /* else: "" trap, ignoring signal */
1047 continue;
1048 }
1049 /* not a trap: special action */
Denis Vlasenkod5762932009-03-31 11:22:57 +00001050 switch (sig) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001051// case SIGCHLD:
1052// G.count_SIGCHLD++;
1053// break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001054 case SIGINT:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001055 bb_putchar('\n');
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001056 G.flag_SIGINT = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001057 break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001058//TODO
1059// case SIGHUP: ...
1060// break;
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00001061 default: /* ignored: */
1062 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001063 break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001064 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00001065 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001066 return last_sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001067}
1068
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001069#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001070
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001071/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1072#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001073/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001074#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1075
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001076/* Restores tty foreground process group, and exits.
1077 * May be called as signal handler for fatal signal
1078 * (will faithfully resend signal to itself, producing correct exit state)
1079 * or called directly with -EXITCODE.
1080 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001081static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001082static void sigexit(int sig)
1083{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001084 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001085 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001086
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001087 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001088 * tty pgrp then, only top-level shell process does that */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001089 if (G_interactive_fd && getpid() == G.root_pid)
1090 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001091
1092 /* Not a signal, just exit */
1093 if (sig <= 0)
1094 _exit(- sig);
1095
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001096 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001097}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001098#else
1099
1100#define disable_restore_tty_pgrp_on_exit() ((void)0)
1101#define enable_restore_tty_pgrp_on_exit() ((void)0)
1102
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001103#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001104
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001105/* Restores tty foreground process group, and exits. */
1106static void hush_exit(int exitcode) NORETURN;
1107static void hush_exit(int exitcode)
1108{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001109 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1110 /* Prevent recursion:
1111 * trap "echo Hi; exit" EXIT; exit
1112 */
1113 char *argv[] = { NULL, G.traps[0], NULL };
1114 G.traps[0] = NULL;
1115 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001116 builtin_eval(argv);
1117 free(argv[1]);
1118 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001119
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001120#if ENABLE_HUSH_JOB
1121 fflush(NULL); /* flush all streams */
1122 sigexit(- (exitcode & 0xff));
1123#else
1124 exit(exitcode);
1125#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001126}
1127
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001128
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001129static const char *set_cwd(void)
1130{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001131 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1132 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001133 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001134 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001135 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1136 if (!G.cwd)
1137 G.cwd = bb_msg_unknown;
1138 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001139}
1140
Denis Vlasenko83506862007-11-23 13:11:42 +00001141
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001142/* Get/check local shell variables */
1143static struct variable *get_local_var(const char *name)
1144{
1145 struct variable *cur;
1146 int len;
1147
1148 if (!name)
1149 return NULL;
1150 len = strlen(name);
1151 for (cur = G.top_var; cur; cur = cur->next) {
1152 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1153 return cur;
1154 }
1155 return NULL;
1156}
1157
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001158static const char *get_local_var_value(const char *src)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001159{
1160 struct variable *var = get_local_var(src);
1161 if (var)
1162 return strchr(var->varstr, '=') + 1;
1163 return NULL;
1164}
1165
1166/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001167 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001168 * flg_export:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001169 * 0: do not export
1170 * 1: export
1171 * -1: if NAME is set, leave export status alone
1172 * if NAME is not set, do not export
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001173 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001174 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001175#if BB_MMU
1176#define set_local_var(str, flg_export, flg_read_only) \
1177 set_local_var(str, flg_export)
1178#endif
1179static int set_local_var(char *str, int flg_export, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001180{
1181 struct variable *cur;
1182 char *value;
1183 int name_len;
1184
1185 value = strchr(str, '=');
1186 if (!value) { /* not expected to ever happen? */
1187 free(str);
1188 return -1;
1189 }
1190
1191 name_len = value - str + 1; /* including '=' */
1192 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1193 while (1) {
1194 if (strncmp(cur->varstr, str, name_len) != 0) {
1195 if (!cur->next) {
1196 /* Bail out. Note that now cur points
1197 * to last var in linked list */
1198 break;
1199 }
1200 cur = cur->next;
1201 continue;
1202 }
1203 /* We found an existing var with this name */
1204 *value = '\0';
1205 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001206#if !BB_MMU
1207 if (!flg_read_only)
1208#endif
1209 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001210 free(str);
1211 return -1;
1212 }
1213 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1214 unsetenv(str); /* just in case */
1215 *value = '=';
1216 if (strcmp(cur->varstr, str) == 0) {
1217 free_and_exp:
1218 free(str);
1219 goto exp;
1220 }
1221 if (cur->max_len >= strlen(str)) {
1222 /* This one is from startup env, reuse space */
1223 strcpy(cur->varstr, str);
1224 goto free_and_exp;
1225 }
1226 /* max_len == 0 signifies "malloced" var, which we can
1227 * (and has to) free */
1228 if (!cur->max_len)
1229 free(cur->varstr);
1230 cur->max_len = 0;
1231 goto set_str_and_exp;
1232 }
1233
1234 /* Not found - create next variable struct */
1235 cur->next = xzalloc(sizeof(*cur));
1236 cur = cur->next;
1237
1238 set_str_and_exp:
1239 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001240#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001241 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001242#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001243 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001244 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001245 cur->flg_export = 1;
1246 if (cur->flg_export) {
1247 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1248 return putenv(cur->varstr);
1249 }
1250 return 0;
1251}
1252
Mike Frysingerd690f682009-03-30 06:50:54 +00001253static int unset_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001254{
1255 struct variable *cur;
1256 struct variable *prev = prev; /* for gcc */
1257 int name_len;
1258
1259 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001260 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001261 name_len = strlen(name);
1262 cur = G.top_var;
1263 while (cur) {
1264 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1265 if (cur->flg_read_only) {
1266 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001267 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001268 }
1269 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1270 * is ro, and we cannot reach this code on the 1st pass */
1271 prev->next = cur->next;
1272 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1273 bb_unsetenv(cur->varstr);
1274 if (!cur->max_len)
1275 free(cur->varstr);
1276 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001277 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001278 }
1279 prev = cur;
1280 cur = cur->next;
1281 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001282 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001283}
1284
Mike Frysinger98c52642009-04-02 10:02:37 +00001285#if ENABLE_SH_MATH_SUPPORT
1286#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1287#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1288static char *endofname(const char *name)
1289{
1290 char *p;
1291
1292 p = (char *) name;
1293 if (!is_name(*p))
1294 return p;
1295 while (*++p) {
1296 if (!is_in_name(*p))
1297 break;
1298 }
1299 return p;
1300}
1301
1302static void arith_set_local_var(const char *name, const char *val, int flags)
1303{
1304 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001305 char *var = xasprintf("%s=%s", name, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001306 set_local_var(var, flags, 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001307}
1308#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001309
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001310
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001311/*
1312 * in_str support
1313 */
1314static int static_get(struct in_str *i)
1315{
1316 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001317 if (ch != '\0')
1318 return ch;
1319 i->p--;
1320 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001321}
1322
1323static int static_peek(struct in_str *i)
1324{
1325 return *i->p;
1326}
1327
1328#if ENABLE_HUSH_INTERACTIVE
1329
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001330static void cmdedit_set_initial_prompt(void)
1331{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001332 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1333 G.PS1 = getenv("PS1");
1334 if (G.PS1 == NULL)
1335 G.PS1 = "\\w \\$ ";
1336 } else
1337 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001338}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001339
1340static const char* setup_prompt_string(int promptmode)
1341{
1342 const char *prompt_str;
1343 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001344 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1345 /* Set up the prompt */
1346 if (promptmode == 0) { /* PS1 */
1347 free((char*)G.PS1);
1348 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1349 prompt_str = G.PS1;
1350 } else
1351 prompt_str = G.PS2;
1352 } else
1353 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001354 debug_printf("result '%s'\n", prompt_str);
1355 return prompt_str;
1356}
1357
1358static void get_user_input(struct in_str *i)
1359{
1360 int r;
1361 const char *prompt_str;
1362
1363 prompt_str = setup_prompt_string(i->promptmode);
1364#if ENABLE_FEATURE_EDITING
1365 /* Enable command line editing only while a command line
1366 * is actually being read */
1367 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001368 G.flag_SIGINT = 0;
1369 /* buglet: SIGINT will not make new prompt to appear _at once_,
1370 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001371 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001372 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001373 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001374 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001375 i->eof_flag = (r < 0);
1376 if (i->eof_flag) { /* EOF/error detected */
1377 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1378 G.user_input_buf[1] = '\0';
1379 }
1380#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001381 do {
1382 G.flag_SIGINT = 0;
1383 fputs(prompt_str, stdout);
1384 fflush(stdout);
1385 G.user_input_buf[0] = r = fgetc(i->file);
1386 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001387//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001388 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001389 i->eof_flag = (r == EOF);
1390#endif
1391 i->p = G.user_input_buf;
1392}
1393
1394#endif /* INTERACTIVE */
1395
1396/* This is the magic location that prints prompts
1397 * and gets data back from the user */
1398static int file_get(struct in_str *i)
1399{
1400 int ch;
1401
1402 /* If there is data waiting, eat it up */
1403 if (i->p && *i->p) {
1404#if ENABLE_HUSH_INTERACTIVE
1405 take_cached:
1406#endif
1407 ch = *i->p++;
1408 if (i->eof_flag && !*i->p)
1409 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001410 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001411 } else {
1412 /* need to double check i->file because we might be doing something
1413 * more complicated by now, like sourcing or substituting. */
1414#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001415 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001416 do {
1417 get_user_input(i);
1418 } while (!*i->p); /* need non-empty line */
1419 i->promptmode = 1; /* PS2 */
1420 i->promptme = 0;
1421 goto take_cached;
1422 }
1423#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001424 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001425 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001426 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001427#if ENABLE_HUSH_INTERACTIVE
1428 if (ch == '\n')
1429 i->promptme = 1;
1430#endif
1431 return ch;
1432}
1433
Denis Vlasenko913a2012009-04-05 22:17:04 +00001434/* All callers guarantee this routine will never
1435 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001436 */
1437static int file_peek(struct in_str *i)
1438{
1439 int ch;
1440 if (i->p && *i->p) {
1441 if (i->eof_flag && !i->p[1])
1442 return EOF;
1443 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001444 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001445 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001446 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001447 i->eof_flag = (ch == EOF);
1448 i->peek_buf[0] = ch;
1449 i->peek_buf[1] = '\0';
1450 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001451 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001452 return ch;
1453}
1454
1455static void setup_file_in_str(struct in_str *i, FILE *f)
1456{
1457 i->peek = file_peek;
1458 i->get = file_get;
1459#if ENABLE_HUSH_INTERACTIVE
1460 i->promptme = 1;
1461 i->promptmode = 0; /* PS1 */
1462#endif
1463 i->file = f;
1464 i->p = NULL;
1465}
1466
1467static void setup_string_in_str(struct in_str *i, const char *s)
1468{
1469 i->peek = static_peek;
1470 i->get = static_get;
1471#if ENABLE_HUSH_INTERACTIVE
1472 i->promptme = 1;
1473 i->promptmode = 0; /* PS1 */
1474#endif
1475 i->p = s;
1476 i->eof_flag = 0;
1477}
1478
1479
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001480/*
1481 * o_string support
1482 */
1483#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001484
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001485static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001486{
1487 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001488 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001489 if (o->data)
1490 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001491}
1492
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001493static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001494{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001495 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001496 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001497}
1498
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001499static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1500{
1501 free(o->data);
1502}
1503
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001504static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001505{
1506 if (o->length + len > o->maxlen) {
1507 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1508 o->data = xrealloc(o->data, 1 + o->maxlen);
1509 }
1510}
1511
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001512static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001513{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001514 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1515 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001516 o->data[o->length] = ch;
1517 o->length++;
1518 o->data[o->length] = '\0';
1519}
1520
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001521static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001522{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001523 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001524 memcpy(&o->data[o->length], str, len);
1525 o->length += len;
1526 o->data[o->length] = '\0';
1527}
1528
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001529#if !BB_MMU
1530static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001531{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001532 o_addblock(o, str, strlen(str));
1533}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001534static void nommu_addchr(o_string *o, int ch)
1535{
1536 if (o)
1537 o_addchr(o, ch);
1538}
1539#else
1540#define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001541#endif
1542
1543static void o_addstr_with_NUL(o_string *o, const char *str)
1544{
1545 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001546}
1547
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001548static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001549{
1550 while (len) {
1551 o_addchr(o, *str);
1552 if (*str++ == '\\'
1553 && (*str != '*' && *str != '?' && *str != '[')
1554 ) {
1555 o_addchr(o, '\\');
1556 }
1557 len--;
1558 }
1559}
1560
Eric Andersen25f27032001-04-26 23:22:31 +00001561/* My analysis of quoting semantics tells me that state information
1562 * is associated with a destination, not a source.
1563 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001564static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001565{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001566 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001567 char *found = strchr("*?[\\", ch);
1568 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001569 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001570 o_grow_by(o, sz);
1571 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001572 o->data[o->length] = '\\';
1573 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001574 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001575 o->data[o->length] = ch;
1576 o->length++;
1577 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001578}
1579
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001580static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001581{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001582 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001583 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001584 sz++;
1585 o->data[o->length] = '\\';
1586 o->length++;
1587 }
1588 o_grow_by(o, sz);
1589 o->data[o->length] = ch;
1590 o->length++;
1591 o->data[o->length] = '\0';
1592}
1593
1594static void o_addQstr(o_string *o, const char *str, int len)
1595{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001596 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001597 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001598 return;
1599 }
1600 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001601 char ch;
1602 int sz;
1603 int ordinary_cnt = strcspn(str, "*?[\\");
1604 if (ordinary_cnt > len) /* paranoia */
1605 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001606 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001607 if (ordinary_cnt == len)
1608 return;
1609 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001610 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001611
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001612 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001613 sz = 1;
1614 if (ch) { /* it is necessarily one of "*?[\\" */
1615 sz++;
1616 o->data[o->length] = '\\';
1617 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001618 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001619 o_grow_by(o, sz);
1620 o->data[o->length] = ch;
1621 o->length++;
1622 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001623 }
1624}
1625
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001626/* A special kind of o_string for $VAR and `cmd` expansion.
1627 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001628 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001629 * list[i] contains an INDEX (int!) into this string data.
1630 * It means that if list[] needs to grow, data needs to be moved higher up
1631 * but list[i]'s need not be modified.
1632 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001633 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001634 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1635 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001636#if DEBUG_EXPAND || DEBUG_GLOB
1637static void debug_print_list(const char *prefix, o_string *o, int n)
1638{
1639 char **list = (char**)o->data;
1640 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1641 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001642
1643 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001644 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1645 prefix, list, n, string_start, o->length, o->maxlen);
1646 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001647 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001648 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1649 o->data + (int)list[i] + string_start,
1650 o->data + (int)list[i] + string_start);
1651 i++;
1652 }
1653 if (n) {
1654 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001655 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001656 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001657 }
1658}
1659#else
1660#define debug_print_list(prefix, o, n) ((void)0)
1661#endif
1662
1663/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1664 * in list[n] so that it points past last stored byte so far.
1665 * It returns n+1. */
1666static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001667{
1668 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001669 int string_start;
1670 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001671
1672 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001673 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1674 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001675 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001676 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001677 /* list[n] points to string_start, make space for 16 more pointers */
1678 o->maxlen += 0x10 * sizeof(list[0]);
1679 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001680 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001681 memmove(list + n + 0x10, list + n, string_len);
1682 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001683 } else {
1684 debug_printf_list("list[%d]=%d string_start=%d\n",
1685 n, string_len, string_start);
1686 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001687 } else {
1688 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001689 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1690 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001691 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1692 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001693 o->has_empty_slot = 0;
1694 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001695 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001696 return n + 1;
1697}
1698
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001699/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001700static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001701{
1702 char **list = (char**)o->data;
1703 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1704
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001705 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001706}
1707
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001708/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001709 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001710static int o_glob(o_string *o, int n)
1711{
1712 glob_t globdata;
1713 int gr;
1714 char *pattern;
1715
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001716 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001717 if (!o->data)
1718 return o_save_ptr_helper(o, n);
1719 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001720 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001721 if (!glob_needed(pattern)) {
1722 literal:
1723 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001724 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001725 return o_save_ptr_helper(o, n);
1726 }
1727
1728 memset(&globdata, 0, sizeof(globdata));
1729 gr = glob(pattern, 0, NULL, &globdata);
1730 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1731 if (gr == GLOB_NOSPACE)
1732 bb_error_msg_and_die("out of memory during glob");
1733 if (gr == GLOB_NOMATCH) {
1734 globfree(&globdata);
1735 goto literal;
1736 }
1737 if (gr != 0) { /* GLOB_ABORTED ? */
1738//TODO: testcase for bad glob pattern behavior
1739 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1740 }
1741 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1742 char **argv = globdata.gl_pathv;
1743 o->length = pattern - o->data; /* "forget" pattern */
1744 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001745 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001746 n = o_save_ptr_helper(o, n);
1747 argv++;
1748 if (!*argv)
1749 break;
1750 }
1751 }
1752 globfree(&globdata);
1753 if (DEBUG_GLOB)
1754 debug_print_list("o_glob returning", o, n);
1755 return n;
1756}
1757
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001758/* If o->o_glob == 1, glob the string so far remembered.
1759 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001760static int o_save_ptr(o_string *o, int n)
1761{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001762 if (o->o_glob) { /* if globbing is requested */
1763 /* If o->has_empty_slot, list[n] was already globbed
1764 * (if it was requested back then when it was filled)
1765 * so don't do that again! */
1766 if (!o->has_empty_slot)
1767 return o_glob(o, n); /* o_save_ptr_helper is inside */
1768 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001769 return o_save_ptr_helper(o, n);
1770}
1771
1772/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001773static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001774{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001775 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001776 int string_start;
1777
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001778 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1779 if (DEBUG_EXPAND)
1780 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001781 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001782 list = (char**)o->data;
1783 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1784 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001785 while (n) {
1786 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001787 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001788 }
1789 return list;
1790}
1791
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001792
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001793/* Expansion can recurse */
1794#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001795static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001796#endif
1797static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001798#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001799#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001800 parse_stream_dquoted(dest, input, dquote_end)
1801#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001802static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001803 o_string *dest,
1804 struct in_str *input,
1805 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001806
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001807/* expand_strvec_to_strvec() takes a list of strings, expands
1808 * all variable references within and returns a pointer to
1809 * a list of expanded strings, possibly with larger number
1810 * of strings. (Think VAR="a b"; echo $VAR).
1811 * This new list is allocated as a single malloc block.
1812 * NULL-terminated list of char* pointers is at the beginning of it,
1813 * followed by strings themself.
1814 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001815
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001816/* Store given string, finalizing the word and starting new one whenever
1817 * we encounter IFS char(s). This is used for expanding variable values.
1818 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1819static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001820{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821 while (1) {
1822 int word_len = strcspn(str, G.ifs);
1823 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001824 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001825 o_addQstr(output, str, word_len);
1826 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001827 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001828 str += word_len;
1829 }
1830 if (!*str) /* EOL - do not finalize word */
1831 break;
1832 o_addchr(output, '\0');
1833 debug_print_list("expand_on_ifs", output, n);
1834 n = o_save_ptr(output, n);
1835 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001836 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001837 debug_print_list("expand_on_ifs[1]", output, n);
1838 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001839}
1840
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001841/* Helper to expand $((...)) and heredoc body. These act as if
1842 * they are in double quotes, with the exception that they are not :).
1843 * Just the rules are similar: "expand only $var and `cmd`"
1844 *
1845 * Returns malloced string.
1846 * As an optimization, we return NULL if expansion is not needed.
1847 */
1848static char *expand_pseudo_dquoted(const char *str)
1849{
1850 char *exp_str;
1851 struct in_str input;
1852 o_string dest = NULL_O_STRING;
1853
1854 if (strchr(str, '$') == NULL
1855#if ENABLE_HUSH_TICK
1856 && strchr(str, '`') == NULL
1857#endif
1858 ) {
1859 return NULL;
1860 }
1861
1862 /* We need to expand. Example:
1863 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1864 */
1865 setup_string_in_str(&input, str);
1866 parse_stream_dquoted(NULL, &dest, &input, EOF);
1867 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1868 exp_str = expand_string_to_string(dest.data);
1869 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1870 o_free_unsafe(&dest);
1871 return exp_str;
1872}
1873
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874/* Expand all variable references in given string, adding words to list[]
1875 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1876 * to be filled). This routine is extremely tricky: has to deal with
1877 * variables/parameters with whitespace, $* and $@, and constructs like
1878 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1879static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001880{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001881 /* or_mask is either 0 (normal case) or 0x80
1882 * (expansion of right-hand side of assignment == 1-element expand.
1883 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001884
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001885 char first_ch, ored_ch;
1886 int i;
1887 const char *val;
Mike Frysingera4f331d2009-04-07 06:03:22 +00001888 char *dyn_val, *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001889
Mike Frysingera4f331d2009-04-07 06:03:22 +00001890 dyn_val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001891 ored_ch = 0;
1892
1893 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1894 debug_print_list("expand_vars_to_list", output, n);
1895 n = o_save_ptr(output, n);
1896 debug_print_list("expand_vars_to_list[0]", output, n);
1897
1898 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1899#if ENABLE_HUSH_TICK
1900 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001901#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001902#if ENABLE_SH_MATH_SUPPORT
1903 char arith_buf[sizeof(arith_t)*3 + 2];
1904#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001905 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001906 debug_print_list("expand_vars_to_list[1]", output, n);
1907 arg = ++p;
1908 p = strchr(p, SPECIAL_VAR_SYMBOL);
1909
1910 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1911 /* "$@" is special. Even if quoted, it can still
1912 * expand to nothing (not even an empty string) */
1913 if ((first_ch & 0x7f) != '@')
1914 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001915
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001916 val = NULL;
1917 switch (first_ch & 0x7f) {
1918 /* Highest bit in first_ch indicates that var is double-quoted */
1919 case '$': /* pid */
1920 val = utoa(G.root_pid);
1921 break;
1922 case '!': /* bg pid */
1923 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1924 break;
1925 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001926 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001927 break;
1928 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001929 if (arg[1] != SPECIAL_VAR_SYMBOL)
1930 /* actually, it's a ${#var} */
1931 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001932 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1933 break;
1934 case '*':
1935 case '@':
1936 i = 1;
1937 if (!G.global_argv[i])
1938 break;
1939 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1940 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001941 smallint sv = output->o_escape;
1942 /* unquoted var's contents should be globbed, so don't escape */
1943 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001944 while (G.global_argv[i]) {
1945 n = expand_on_ifs(output, n, G.global_argv[i]);
1946 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1947 if (G.global_argv[i++][0] && G.global_argv[i]) {
1948 /* this argv[] is not empty and not last:
1949 * put terminating NUL, start new word */
1950 o_addchr(output, '\0');
1951 debug_print_list("expand_vars_to_list[2]", output, n);
1952 n = o_save_ptr(output, n);
1953 debug_print_list("expand_vars_to_list[3]", output, n);
1954 }
1955 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001956 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001957 } else
1958 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1959 * and in this case should treat it like '$*' - see 'else...' below */
1960 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1961 while (1) {
1962 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1963 if (++i >= G.global_argc)
1964 break;
1965 o_addchr(output, '\0');
1966 debug_print_list("expand_vars_to_list[4]", output, n);
1967 n = o_save_ptr(output, n);
1968 }
1969 } else { /* quoted $*: add as one word */
1970 while (1) {
1971 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1972 if (!G.global_argv[++i])
1973 break;
1974 if (G.ifs[0])
1975 o_addchr(output, G.ifs[0]);
1976 }
1977 }
1978 break;
1979 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1980 /* "Empty variable", used to make "" etc to not disappear */
1981 arg++;
1982 ored_ch = 0x80;
1983 break;
1984#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001985 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001986 *p = '\0';
1987 arg++;
1988//TODO: can we just stuff it into "output" directly?
1989 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001990 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001991 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1992 val = subst_result.data;
1993 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001994#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001995#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001996 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001997 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00001998 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00001999 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002000 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002001
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002002 arg++; /* skip '+' */
2003 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002004 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002005
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002006 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002007 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002008 hooks.setvar = arith_set_local_var;
2009 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002010 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2011 free(exp_str);
2012
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002013 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002014 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002015 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002016 case -3:
2017 msg = "exponent less than 0";
2018 break;
2019 case -2:
2020 msg = "divide by 0";
2021 break;
2022 case -5:
2023 msg = "expression recursion loop detected";
2024 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002025 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002026 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002027 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002028 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002029 sprintf(arith_buf, arith_t_fmt, res);
2030 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002031 break;
2032 }
2033#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002034 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002035 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002036 bool exp_len = false;
2037 bool exp_null = false;
2038 char *var = arg;
2039 char exp_save = exp_save; /* for compiler */
2040 char exp_op = exp_op; /* for compiler */
2041 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002042 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002043
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002044 *p = '\0';
2045 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002046
2047 /* prepare for expansions */
2048 if (var[0] == '#') {
2049 /* handle length expansion ${#var} */
2050 exp_len = true;
2051 ++var;
2052 } else {
2053 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002054 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002055 if (!var[exp_off])
2056 exp_off = 0;
2057 if (exp_off) {
2058 exp_save = var[exp_off];
2059 exp_null = exp_save == ':';
2060 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002061 if (exp_null)
2062 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002063 exp_op = *exp_word++;
2064 var[exp_off] = '\0';
2065 }
2066 }
2067
2068 /* lookup the variable in question */
2069 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002070 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002071 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002072 if (i < G.global_argc)
2073 val = G.global_argv[i];
2074 /* else val remains NULL: $N with too big N */
2075 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002076 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002077
2078 /* handle any expansions */
2079 if (exp_len) {
2080 debug_printf_expand("expand: length of '%s' = ", val);
2081 val = utoa(val ? strlen(val) : 0);
2082 debug_printf_expand("%s\n", val);
2083 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002084 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002085 if (val) {
2086 /* we need to do a pattern match */
2087 bool zero;
2088 char *loc;
2089 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
2090 if (exp_op == *exp_word) /* ## or %% */
2091 ++exp_word;
2092 val = dyn_val = xstrdup(val);
2093 loc = scan(dyn_val, exp_word, zero);
2094 if (zero)
2095 val = loc;
2096 else
2097 *loc = '\0';
2098 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002099 } else {
2100 /* we need to do an expansion */
2101 int exp_test = (!val || (exp_null && !val[0]));
2102 if (exp_op == '+')
2103 exp_test = !exp_test;
2104 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2105 exp_null ? "true" : "false", exp_test);
2106 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002107 if (exp_op == '?') {
2108//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002109 /* ${var?[error_msg_if_unset]} */
2110 /* ${var:?[error_msg_if_unset_or_null]} */
2111 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002112 die_if_script("%s: %s",
2113 var,
2114 exp_word[0] ? exp_word : "parameter null or not set"
2115 );
2116 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002117 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002118 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002119
Mike Frysingera4f331d2009-04-07 06:03:22 +00002120 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002121 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002122 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002123 /* mimic bash message */
2124 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002125 val = NULL;
2126 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002127 char *new_var = xasprintf("%s=%s", var, val);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002128 set_local_var(new_var, -1, 0);
2129 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002130 }
2131 }
2132 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002133
Mike Frysinger6379bb42009-03-28 18:55:03 +00002134 var[exp_off] = exp_save;
2135 }
2136
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002137 arg[0] = first_ch;
2138#if ENABLE_HUSH_TICK
2139 store_val:
2140#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002141 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002142 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002143 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002144 /* unquoted var's contents should be globbed, so don't escape */
2145 smallint sv = output->o_escape;
2146 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002147 n = expand_on_ifs(output, n, val);
2148 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002149 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002150 }
2151 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002152 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002153 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002154 } /* default: */
2155 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002156 if (val) {
2157 o_addQstr(output, val, strlen(val));
2158 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002159 free(dyn_val);
2160 dyn_val = NULL;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002161 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002162 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002163 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002164
2165#if ENABLE_HUSH_TICK
2166 o_free(&subst_result);
2167#endif
2168 arg = ++p;
2169 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2170
2171 if (arg[0]) {
2172 debug_print_list("expand_vars_to_list[a]", output, n);
2173 /* this part is literal, and it was already pre-quoted
2174 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002175 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002176 debug_print_list("expand_vars_to_list[b]", output, n);
2177 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2178 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2179 ) {
2180 n--;
2181 /* allow to reuse list[n] later without re-growth */
2182 output->has_empty_slot = 1;
2183 } else {
2184 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002185 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002186 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002187}
2188
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002189static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002190{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002191 int n;
2192 char **list;
2193 char **v;
2194 o_string output = NULL_O_STRING;
2195
2196 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002197 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002198 /* (unquoted $var will temporarily switch it off) */
2199 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002200 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002201
2202 n = 0;
2203 v = argv;
2204 while (*v) {
2205 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2206 v++;
2207 }
2208 debug_print_list("expand_variables", &output, n);
2209
2210 /* output.data (malloced in one block) gets returned in "list" */
2211 list = o_finalize_list(&output, n);
2212 debug_print_strings("expand_variables[1]", list);
2213 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002214}
2215
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002216static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002217{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002218 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002219}
2220
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002221/* Used for expansion of right hand of assignments */
2222/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2223 * "v=/bin/c*" */
2224static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002225{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002226 char *argv[2], **list;
2227
2228 argv[0] = (char*)str;
2229 argv[1] = NULL;
2230 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2231 if (HUSH_DEBUG)
2232 if (!list[0] || list[1])
2233 bb_error_msg_and_die("BUG in varexp2");
2234 /* actually, just move string 2*sizeof(char*) bytes back */
2235 overlapping_strcpy((char*)list, list[0]);
2236 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2237 return (char*)list;
2238}
2239
2240/* Used for "eval" builtin */
2241static char* expand_strvec_to_string(char **argv)
2242{
2243 char **list;
2244
2245 list = expand_variables(argv, 0x80);
2246 /* Convert all NULs to spaces */
2247 if (list[0]) {
2248 int n = 1;
2249 while (list[n]) {
2250 if (HUSH_DEBUG)
2251 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2252 bb_error_msg_and_die("BUG in varexp3");
2253 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2254 n++;
2255 }
2256 }
2257 overlapping_strcpy((char*)list, list[0]);
2258 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2259 return (char*)list;
2260}
2261
2262static char **expand_assignments(char **argv, int count)
2263{
2264 int i;
2265 char **p = NULL;
2266 /* Expand assignments into one string each */
2267 for (i = 0; i < count; i++) {
2268 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2269 }
2270 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002271}
2272
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002273
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002274#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002275/* never called */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002276void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002277
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002278static void reset_traps_to_defaults(void)
2279{
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002280 enum {
2281 JOBSIGS = (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
2282 };
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002283 unsigned sig;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002284
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002285 if (!G.traps && !(G.non_DFL_mask & JOBSIGS))
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002286 return;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002287
2288 /* This function is always called in a child shell.
2289 * Child shells are not interactive.
2290 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2291 * Testcase: (while :; do :; done) + ^Z should background.
2292 */
2293 G.non_DFL_mask &= ~JOBSIGS;
2294 sigdelset(&G.blocked_set, SIGTTIN);
2295 sigdelset(&G.blocked_set, SIGTTOU);
2296 sigdelset(&G.blocked_set, SIGTSTP);
2297
2298 if (G.traps) for (sig = 0; sig < NSIG; sig++) {
2299 if (!G.traps[sig]) {
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002300 continue;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002301 }
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002302 free(G.traps[sig]);
2303 G.traps[sig] = NULL;
2304 /* There is no signal for 0 (EXIT) */
2305 if (sig == 0)
2306 continue;
2307 /* there was a trap handler, we are removing it
2308 * (if sig has non-DFL handling,
2309 * we don't need to do anything) */
2310 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2311 continue;
2312 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002313 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002314 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002315}
2316
2317#else /* !BB_MMU */
2318
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002319static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2320static void re_execute_shell(char ***to_free, 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 Vlasenko27014ed2009-04-15 21:48:23 +00002362 *to_free = 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}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002420#endif /* !BB_MMU */
2421
2422
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002423static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002424{
2425 struct fd_pair pair;
2426 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002427 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002428 /* the _body_ of heredoc (misleading field name) */
2429 const char *heredoc = redir->rd_filename;
2430 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002431#if !BB_MMU
2432 char **to_free;
2433#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002434
2435 expanded = NULL;
2436 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2437 expanded = expand_pseudo_dquoted(heredoc);
2438 if (expanded)
2439 heredoc = expanded;
2440 }
2441 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002442
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002443 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002444 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002445 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002446
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002447 /* Try writing without forking. Newer kernels have
2448 * dynamically growing pipes. Must use non-blocking write! */
2449 ndelay_on(pair.wr);
2450 while (1) {
2451 written = write(pair.wr, heredoc, len);
2452 if (written <= 0)
2453 break;
2454 len -= written;
2455 if (len == 0) {
2456 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002457 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002458 return;
2459 }
2460 heredoc += written;
2461 }
2462 ndelay_off(pair.wr);
2463
2464 /* Okay, pipe buffer was not big enough */
2465 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002466 * for the unsuspecting parent process. Child creates a grandchild
2467 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002468 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002469#if !BB_MMU
2470 to_free = NULL;
2471#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002472 pid = vfork();
2473 if (pid < 0)
2474 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002475 if (pid == 0) {
2476 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002477 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002478 pid = BB_MMU ? fork() : vfork();
2479 if (pid < 0)
2480 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2481 if (pid != 0)
2482 _exit(0);
2483 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002484 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002485#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002486 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002487 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002488#else
2489 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002490 xmove_fd(pair.wr, STDOUT_FILENO);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002491 re_execute_shell(&to_free, heredoc, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002492#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002493 }
2494 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002495 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002496#if !BB_MMU
2497 free(to_free);
2498#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002499 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002500 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002501 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002502}
2503
Eric Andersen25f27032001-04-26 23:22:31 +00002504/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2505 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002506static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002507{
2508 int openfd, mode;
2509 struct redir_struct *redir;
2510
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002511 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002512 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002513 /* rd_fd<<HERE case */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002514 if (squirrel && redir->rd_fd < 3) {
2515 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002516 }
2517 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2518 * of the heredoc */
2519 debug_printf_parse("set heredoc '%s'\n",
2520 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002521 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002522 continue;
2523 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002524
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002525 if (redir->rd_dup == REDIRFD_TO_FILE) {
2526 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002527 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002528 if (redir->rd_filename == NULL) {
2529 /* Something went wrong in the parse.
2530 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002531 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002532 continue;
2533 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002534 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002535 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002536 openfd = open_or_warn(p, mode);
2537 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002538 if (openfd < 0) {
2539 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002540 * bash and ash both lose it as well (though zsh doesn't!) */
2541//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002542 return 1;
2543 }
2544 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002545 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002546 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002547 }
2548
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002549 if (openfd != redir->rd_fd) {
2550 if (squirrel && redir->rd_fd < 3) {
2551 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002552 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002553 if (openfd == REDIRFD_CLOSE) {
2554 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002555 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002556 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002557 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002558 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002559 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002560 }
Eric Andersen25f27032001-04-26 23:22:31 +00002561 }
2562 }
2563 return 0;
2564}
2565
2566static void restore_redirects(int squirrel[])
2567{
2568 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002569 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002570 fd = squirrel[i];
2571 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002572 /* We simply die on error */
2573 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002574 }
2575 }
2576}
2577
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002578
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002579static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002580
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002581/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002582static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002583{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002584 char **p;
2585 struct command *command;
2586 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002587 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002588
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002589 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002590 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002591 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002592 for (i = 0; i < pi->num_cmds; i++) {
2593 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002594 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002595 if (command->argv) {
2596 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002597 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002598 }
2599 free_strings(command->argv);
2600 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002601 }
2602 /* not "else if": on syntax error, we may have both! */
2603 if (command->group) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002604 debug_printf_clean(" begin group (grp_type:%d)\n",
2605 command->grp_type);
2606 free_pipe_list(command->group);
2607 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002608 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002609 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002610 /* else is crucial here.
2611 * If group != NULL, child_func is meaningless */
2612#if ENABLE_HUSH_FUNCTIONS
2613 else if (command->child_func) {
2614 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2615 command->child_func->parent_cmd = NULL;
2616 }
2617#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002618#if !BB_MMU
2619 free(command->group_as_string);
2620 command->group_as_string = NULL;
2621#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002622 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002623 debug_printf_clean(" redirect %d%s",
2624 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002625 /* guard against the case >$FOO, where foo is unset or blank */
2626 if (r->rd_filename) {
2627 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2628 free(r->rd_filename);
2629 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002630 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002631 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002632 rnext = r->next;
2633 free(r);
2634 }
2635 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002636 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002637 free(pi->cmds); /* children are an array, they get freed all at once */
2638 pi->cmds = NULL;
2639#if ENABLE_HUSH_JOB
2640 free(pi->cmdtext);
2641 pi->cmdtext = NULL;
2642#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002643}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002644
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002645static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002646{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002647 struct pipe *pi, *next;
2648
2649 for (pi = head; pi; pi = next) {
2650#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002651 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002652#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002653 free_pipe(pi);
2654 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002655 next = pi->next;
2656 /*pi->next = NULL;*/
2657 free(pi);
2658 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002659}
2660
2661
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002662static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002663#if BB_MMU
2664#define parse_stream(pstring, input, end_trigger) \
2665 parse_stream(input, end_trigger)
2666#endif
2667static struct pipe *parse_stream(char **pstring,
2668 struct in_str *input,
2669 int end_trigger);
2670static void parse_and_run_string(const char *s);
2671
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002672
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002673static const struct built_in_command* find_builtin(const char *name)
2674{
2675 const struct built_in_command *x;
2676 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2677 if (strcmp(name, x->cmd) != 0)
2678 continue;
2679 debug_printf_exec("found builtin '%s'\n", name);
2680 return x;
2681 }
2682 return NULL;
2683}
2684
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002685#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002686static const struct function *find_function(const char *name)
2687{
2688 const struct function *funcp = G.top_func;
2689 while (funcp) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002690 if (strcmp(name, funcp->name) == 0) {
2691 break;
2692 }
2693 funcp = funcp->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002694 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002695 debug_printf_exec("found function '%s'\n", name);
2696 return funcp;
2697}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002698
Denis Vlasenkobc569742009-04-12 20:35:19 +00002699/* Note: takes ownership on name ptr */
2700static struct function *new_function(char *name)
2701{
2702 struct function *funcp;
2703 struct function **funcpp = &G.top_func;
2704
2705 while ((funcp = *funcpp) != NULL) {
2706 struct command *cmd;
2707
2708 if (strcmp(funcp->name, name) != 0) {
2709 funcpp = &funcp->next;
2710 continue;
2711 }
2712
2713 cmd = funcp->parent_cmd;
2714 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2715 if (!cmd) {
2716 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2717 free(funcp->name);
2718 /* Note: if !funcp->body, do not free body_as_string!
2719 * This is a special case of "-F name body" function:
2720 * body_as_string was not malloced! */
2721 if (funcp->body) {
2722 free_pipe_list(funcp->body);
2723#if !BB_MMU
2724 free(funcp->body_as_string);
2725#endif
2726 }
2727 } else {
2728 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2729 cmd->argv[0] = funcp->name;
2730 cmd->group = funcp->body;
2731#if !BB_MMU
2732 cmd->group_as_string = funcp->body_as_string;
2733#endif
2734 }
2735 goto skip;
2736 }
2737 debug_printf_exec("remembering new function '%s'\n", command->argv[0]);
2738 funcp = *funcpp = xzalloc(sizeof(*funcp));
2739 /*funcp->next = NULL;*/
2740 skip:
2741 funcp->name = name;
2742 return funcp;
2743}
2744
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002745#if BB_MMU
2746#define exec_function(nommu_save, funcp, argv) \
2747 exec_function(funcp, argv)
2748#endif
2749static void exec_function(nommu_save_t *nommu_save,
2750 const struct function *funcp,
2751 char **argv) NORETURN;
2752static void exec_function(nommu_save_t *nommu_save,
2753 const struct function *funcp,
2754 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002755{
2756# if BB_MMU
2757 int n = 1;
2758
2759 argv[0] = G.global_argv[0];
2760 G.global_argv = argv;
2761 while (*++argv)
2762 n++;
2763 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002764 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002765 n = run_list(funcp->body);
2766 fflush(NULL);
2767 _exit(n);
2768# else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002769 re_execute_shell(&nommu_save->argv_from_re_execing,
2770 funcp->body_as_string,
2771 G.global_argv[0],
2772 argv + 1);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002773# endif
2774}
2775
2776static int run_function(const struct function *funcp, char **argv)
2777{
2778 int n;
2779 char **pp;
2780 char *sv_argv0;
2781 smallint sv_g_malloced;
2782 int sv_g_argc;
2783 char **sv_g_argv;
2784
2785 sv_argv0 = argv[0];
2786 sv_g_malloced = G.global_args_malloced;
2787 sv_g_argc = G.global_argc;
2788 sv_g_argv = G.global_argv;
2789
2790 pp = argv;
2791 n = 1;
2792 while (*++pp)
2793 n++;
2794
2795 argv[0] = G.global_argv[0]; /* retain $0 */
2796 G.global_args_malloced = 0;
2797 G.global_argc = n;
2798 G.global_argv = argv;
2799
Denis Vlasenkobc569742009-04-12 20:35:19 +00002800 /* On MMU, funcp->body is always non-NULL */
2801#if !BB_MMU
2802 if (!funcp->body) {
2803 /* Function defined by -F */
2804 parse_and_run_string(funcp->body_as_string);
2805 n = G.last_exitcode;
2806 } else
2807#endif
2808 {
2809 n = run_list(funcp->body);
2810 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002811
2812 if (G.global_args_malloced) {
2813 /* function ran "set -- arg1 arg2 ..." */
2814 pp = G.global_argv;
2815 while (*++pp)
2816 free(*pp);
2817 free(G.global_argv);
2818 }
2819
2820 argv[0] = sv_argv0;
2821 G.global_args_malloced = sv_g_malloced;
2822 G.global_argc = sv_g_argc;
2823 G.global_argv = sv_g_argv;
2824
2825 return n;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002826}
2827#endif
2828
2829
Denis Vlasenkocc90f442009-04-08 16:40:34 +00002830#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002831#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2832 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2833#define pseudo_exec(nommu_save, command, argv_expanded) \
2834 pseudo_exec(command, argv_expanded)
2835#endif
2836
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002837/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00002838 * Never returns.
2839 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00002840 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002841 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002842static void pseudo_exec_argv(nommu_save_t *nommu_save,
2843 char **argv, int assignment_cnt,
2844 char **argv_expanded) NORETURN;
2845static void pseudo_exec_argv(nommu_save_t *nommu_save,
2846 char **argv, int assignment_cnt,
2847 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00002848{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002849 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002850
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002851 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002852 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002853 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002854
Denis Vlasenko9504e442008-10-29 01:19:15 +00002855 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002856#if BB_MMU
2857 putenv_all(new_env);
2858 free(new_env); /* optional */
2859#else
2860 nommu_save->new_env = new_env;
2861 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002862#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002863 if (argv_expanded) {
2864 argv = argv_expanded;
2865 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00002866 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002867#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002868 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002869#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002870 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002871
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002872#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
2873 if (strchr(argv[0], '/') != NULL)
2874 goto skip;
2875#endif
2876
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002877 /* On NOMMU, we must never block!
2878 * Example: { sleep 99999 | read line } & echo Ok
2879 * read builtin will block on read syscall, leaving parent blocked
2880 * in vfork. Therefore we can't do this:
2881 */
2882#if BB_MMU
2883 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00002884 * Depending on context, this might be redundant. But it's
2885 * easier to waste a few CPU cycles than it is to figure out
2886 * if this is one of those cases.
2887 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002888 {
2889 int rcode;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002890 const struct built_in_command *x = find_builtin(argv[0]);
2891 if (x) {
2892 rcode = x->function(argv);
2893 fflush(NULL);
2894 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00002895 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002896 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002897#endif
2898#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002899 /* Check if the command matches any functions */
2900 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002901 const struct function *funcp = find_function(argv[0]);
2902 if (funcp) {
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002903 exec_function(nommu_save, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002904 }
2905 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002906#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00002907
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002908#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002909 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002910 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002911 int a = find_applet_by_name(argv[0]);
2912 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002913# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002914 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002915 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002916 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002917 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002918# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002919 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002920 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002921 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2922 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002923 /* If they called chroot or otherwise made the binary no longer
2924 * executable, fall through */
2925 }
2926 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002927#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002928
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002929#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002930 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002931#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002932 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002933 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002934 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002935 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002936 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002937}
2938
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002939/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00002940 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002941static void pseudo_exec(nommu_save_t *nommu_save,
2942 struct command *command,
2943 char **argv_expanded) NORETURN;
2944static void pseudo_exec(nommu_save_t *nommu_save,
2945 struct command *command,
2946 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002947{
Denis Vlasenko552433b2009-04-04 19:29:21 +00002948 if (command->argv) {
2949 pseudo_exec_argv(nommu_save, command->argv,
2950 command->assignment_cnt, argv_expanded);
2951 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002952
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002953 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00002954 /* Cases when we are here:
2955 * ( list )
2956 * { list } &
2957 * ... | ( list ) | ...
2958 * ... | { list } | ...
2959 */
2960#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002961 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002962 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002963 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002964 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002965 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002966 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002967 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002968#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002969 re_execute_shell(&nommu_save->argv_from_re_execing,
2970 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002971 G.global_argv[0],
2972 G.global_argv + 1);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002973#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002974 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002975
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002976 /* Case when we are here: ... | >file */
2977 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002978 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002979}
2980
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002981#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002982static const char *get_cmdtext(struct pipe *pi)
2983{
2984 char **argv;
2985 char *p;
2986 int len;
2987
2988 /* This is subtle. ->cmdtext is created only on first backgrounding.
2989 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002990 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002991 if (pi->cmdtext)
2992 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002993 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002994 if (!argv || !argv[0]) {
2995 pi->cmdtext = xzalloc(1);
2996 return pi->cmdtext;
2997 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002998
2999 len = 0;
3000 do len += strlen(*argv) + 1; while (*++argv);
3001 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003002 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003003 do {
3004 len = strlen(*argv);
3005 memcpy(p, *argv, len);
3006 p += len;
3007 *p++ = ' ';
3008 } while (*++argv);
3009 p[-1] = '\0';
3010 return pi->cmdtext;
3011}
3012
Eric Andersenbafd94f2001-05-02 16:11:59 +00003013static void insert_bg_job(struct pipe *pi)
3014{
3015 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003016 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003017
3018 /* Linear search for the ID of the job to use */
3019 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003020 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003021 if (thejob->jobid >= pi->jobid)
3022 pi->jobid = thejob->jobid + 1;
3023
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003024 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003025 if (!G.job_list) {
3026 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003027 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003028 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003029 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003030 thejob->next = xmalloc(sizeof(*thejob));
3031 thejob = thejob->next;
3032 }
3033
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003034 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00003035 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003036 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3037 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
3038 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003039// TODO: do we really need to have so many fields which are just dead weight
3040// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003041 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003042 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003043 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003044 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003045 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003046
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003047 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00003048 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003049 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003050 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003051 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003052 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003053}
3054
Eric Andersenbafd94f2001-05-02 16:11:59 +00003055static void remove_bg_job(struct pipe *pi)
3056{
3057 struct pipe *prev_pipe;
3058
Denis Vlasenko87a86552008-07-29 19:43:10 +00003059 if (pi == G.job_list) {
3060 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003061 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003062 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003063 while (prev_pipe->next != pi)
3064 prev_pipe = prev_pipe->next;
3065 prev_pipe->next = pi->next;
3066 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003067 if (G.job_list)
3068 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003069 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003070 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003071}
Eric Andersen028b65b2001-06-28 01:10:11 +00003072
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003073/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003074static void delete_finished_bg_job(struct pipe *pi)
3075{
3076 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003077 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003078 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003079 free(pi);
3080}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003081#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003082
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003083/* Check to see if any processes have exited -- if they
3084 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003085static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003086{
Eric Andersenc798b072001-06-22 06:23:03 +00003087 int attributes;
3088 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003089#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003090 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003091#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003092 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003093 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003094
Denis Vlasenkod5762932009-03-31 11:22:57 +00003095 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3096
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003097 errno = 0;
3098// if (G.handled_SIGCHLD == G.count_SIGCHLD)
3099// /* avoid doing syscall, nothing there anyway */
3100// return rcode;
3101
Eric Andersenc798b072001-06-22 06:23:03 +00003102 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003103 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003104 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003105
Denis Vlasenko1359da62007-04-21 23:27:30 +00003106/* Do we do this right?
3107 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003108 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003109 * [3]+ Stopped sleep 20 | false
3110 * bash-3.00# echo $?
3111 * 1 <========== bg pipe is not fully done, but exitcode is already known!
3112 */
3113
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003114//FIXME: non-interactive bash does not continue even if all processes in fg pipe
3115//are stopped. Testcase: "cat | cat" in a script (not on command line)
3116// + killall -STOP cat
3117
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003118 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003119 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003120 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003121 int dead;
3122
3123// i = G.count_SIGCHLD;
3124 childpid = waitpid(-1, &status, attributes);
3125 if (childpid <= 0) {
3126 if (childpid && errno != ECHILD)
3127 bb_perror_msg("waitpid");
3128// else /* Until next SIGCHLD, waitpid's are useless */
3129// G.handled_SIGCHLD = i;
3130 break;
3131 }
3132 dead = WIFEXITED(status) || WIFSIGNALED(status);
3133
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003134#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003135 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003136 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003137 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3138 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003139 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003140 childpid, WTERMSIG(status), WEXITSTATUS(status));
3141 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003142 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003143 childpid, WEXITSTATUS(status));
3144#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003145 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003146 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003147 for (i = 0; i < fg_pipe->num_cmds; i++) {
3148 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3149 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003150 continue;
3151 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
3152 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003153 fg_pipe->cmds[i].pid = 0;
3154 fg_pipe->alive_cmds--;
3155 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003156 /* last process gives overall exitstatus */
3157 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003158 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003159 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003160 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003161 fg_pipe->cmds[i].is_stopped = 1;
3162 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003163 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003164 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3165 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3166 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003167 /* All processes in fg pipe have exited/stopped */
3168#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003169 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003170 insert_bg_job(fg_pipe);
3171#endif
3172 return rcode;
3173 }
3174 /* There are still running processes in the fg pipe */
3175 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003176 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003177 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003178 }
3179
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003180#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003181 /* We asked to wait for bg or orphaned children */
3182 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003183 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003184 for (i = 0; i < pi->num_cmds; i++) {
3185 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003186 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003187 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003188 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003189 /* Happens when shell is used as init process (init=/bin/sh) */
3190 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003191 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003192
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003193 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003194 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003195 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003196 pi->cmds[i].pid = 0;
3197 pi->alive_cmds--;
3198 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003199 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003200 printf(JOB_STATUS_FORMAT, pi->jobid,
3201 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003202 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003203 }
3204 } else {
3205 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003206 pi->cmds[i].is_stopped = 1;
3207 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003208 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003209#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003210 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003211
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003212 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003213}
3214
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003215#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003216static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3217{
3218 pid_t p;
3219 int rcode = checkjobs(fg_pipe);
3220 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00003221 p = getpgid(0); /* pgid of our process */
3222 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003223 tcsetpgrp(G_interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00003224 return rcode;
3225}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003226#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003227
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003228/* Start all the jobs, but don't wait for anything to finish.
3229 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003230 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003231 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003232 * to finish to determine the exit status of the pipe. If the pipe
3233 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003234 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003235 * return value.
3236 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003237 * Returns -1 only if started some children. IOW: we have to
3238 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003239 *
3240 * The only case when we do not need to [v]fork is when the pipe
3241 * is single, non-backgrounded, non-subshell command. Examples:
3242 * cmd ; ... { list } ; ...
3243 * cmd && ... { list } && ...
3244 * cmd || ... { list } || ...
3245 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3246 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003247 * with run_list(). If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003248 *
3249 * Cases when we must fork:
3250 * non-single: cmd | cmd
3251 * backgrounded: cmd & { list } &
3252 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003253 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003254static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003255{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003256 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003257 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003258 int nextin;
3259 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003260 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003261 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003262 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003263 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003264 /* it is not always needed, but we aim to smaller code */
3265 int squirrel[] = { -1, -1, -1 };
3266 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003267
Denis Vlasenko552433b2009-04-04 19:29:21 +00003268 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003269 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003270
Denis Vlasenko552433b2009-04-04 19:29:21 +00003271 USE_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003272 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003273 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003274 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003275
Denis Vlasenko552433b2009-04-04 19:29:21 +00003276 if (pi->num_cmds != 1
3277 || pi->followup == PIPE_BG
3278 || command->grp_type == GRP_SUBSHELL
3279 ) {
3280 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003281 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003282
Denis Vlasenko552433b2009-04-04 19:29:21 +00003283 pi->alive_cmds = 1;
3284
3285 debug_printf_exec(": group:%p argv:'%s'\n",
3286 command->group, command->argv ? command->argv[0] : "NONE");
3287
3288 if (command->group) {
3289#if ENABLE_HUSH_FUNCTIONS
3290 if (command->grp_type == GRP_FUNCTION) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003291 /* "executing" func () { list } */
3292 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003293
Denis Vlasenkobc569742009-04-12 20:35:19 +00003294 funcp = new_function(command->argv[0]);
3295 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003296 funcp->body = command->group;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003297#if !BB_MMU
3298 funcp->body_as_string = command->group_as_string;
3299 command->group_as_string = NULL;
3300#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003301 command->group = NULL;
3302 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003303 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3304 funcp->parent_cmd = command;
3305 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003306
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003307 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3308 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003309 return EXIT_SUCCESS;
3310 }
3311#endif
3312 /* { list } */
3313 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003314 rcode = 1; /* exitcode if redir failed */
3315 if (setup_redirects(command, squirrel) == 0) {
3316 debug_printf_exec(": run_list\n");
3317 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003318 }
Eric Andersen04407e52001-06-07 16:42:05 +00003319 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003320 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003321 debug_leave();
3322 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003323 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003324 }
3325
Denis Vlasenko552433b2009-04-04 19:29:21 +00003326 argv = command->argv ? command->argv : (char **) &null_ptr;
3327 {
3328 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003329#if ENABLE_HUSH_FUNCTIONS
3330 const struct function *funcp;
3331#else
3332 enum { funcp = 0 };
3333#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003334 char **new_env = NULL;
3335 char **old_env = NULL;
3336
Denis Vlasenko552433b2009-04-04 19:29:21 +00003337 if (argv[command->assignment_cnt] == NULL) {
3338 /* Assignments, but no command */
3339 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003340 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003341 restore_redirects(squirrel);
3342 /* Set shell variables */
3343 while (*argv) {
3344 p = expand_string_to_string(*argv);
3345 debug_printf_exec("set shell var:'%s'->'%s'\n",
3346 *argv, p);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003347 set_local_var(p, 0, 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003348 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003349 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003350 /* Do we need to flag set_local_var() errors?
3351 * "assignment to readonly var" and "putenv error"
3352 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003353 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003354 debug_leave();
3355 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003356 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003357 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003358
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003359 /* Expand the rest into (possibly) many strings each */
Denis Vlasenko552433b2009-04-04 19:29:21 +00003360 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003361
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003362 x = find_builtin(argv_expanded[0]);
3363#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003364 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003365 if (!x)
3366 funcp = find_function(argv_expanded[0]);
3367#endif
3368 if (x || funcp) {
3369 if (!funcp) {
3370 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3371 debug_printf("exec with redirects only\n");
3372 rcode = setup_redirects(command, NULL);
3373 goto clean_up_and_ret1;
3374 }
Eric Andersen25f27032001-04-26 23:22:31 +00003375 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003376 /* XXX setup_redirects acts on file descriptors, not FILEs.
3377 * This is perfect for work that comes after exec().
3378 * Is it really safe for inline use? Experimentally,
3379 * things seem to work with glibc. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003380 rcode = setup_redirects(command, squirrel);
3381 if (rcode == 0) {
3382 new_env = expand_assignments(argv, command->assignment_cnt);
3383 old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003384 if (!funcp) {
3385 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003386 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003387 rcode = x->function(argv_expanded) & 0xff;
3388 }
3389#if ENABLE_HUSH_FUNCTIONS
3390 else {
3391 debug_printf_exec(": function '%s' '%s'...\n",
3392 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003393 rcode = run_function(funcp, argv_expanded) & 0xff;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003394 }
3395#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003396 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003397#if ENABLE_FEATURE_SH_STANDALONE
3398 clean_up_and_ret:
3399#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003400 restore_redirects(squirrel);
3401 free_strings_and_unsetenv(new_env, 1);
3402 putenv_all(old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003403 /* Free the pointers, but the strings themselves
3404 * are in environ now, don't use free_strings! */
3405 free(old_env);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003406 clean_up_and_ret1:
3407 free(argv_expanded);
3408 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003409 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003410 debug_printf_exec("run_pipe return %d\n", rcode);
3411 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003412 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003413
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003414#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003415 i = find_applet_by_name(argv_expanded[0]);
3416 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003417 rcode = setup_redirects(command, squirrel);
3418 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003419 new_env = expand_assignments(argv, command->assignment_cnt);
3420 old_env = putenv_all_and_save_old(new_env);
3421 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003422 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003423 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003424 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003425 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003426 }
3427#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003428 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003429 }
3430
Denis Vlasenko552433b2009-04-04 19:29:21 +00003431 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003432 /* NB: argv_expanded may already be created, and that
3433 * might include `cmd` runs! Do not rerun it! We *must*
3434 * use argv_expanded if it's non-NULL */
3435
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003436 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003437 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003438 nextin = 0;
3439
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003440 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00003441#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003442 volatile nommu_save_t nommu_save;
3443 nommu_save.new_env = NULL;
3444 nommu_save.old_env = NULL;
3445 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003446 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003447#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003448 command = &(pi->cmds[i]);
3449 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003450 debug_printf_exec(": pipe member '%s' '%s'...\n",
3451 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003452 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003453 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003454 }
Eric Andersen25f27032001-04-26 23:22:31 +00003455
3456 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003457 pipefds[0] = 0;
3458 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003459 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003460 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003461
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003462 command->pid = BB_MMU ? fork() : vfork();
3463 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003464#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003465 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003466
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003467 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003468 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003469 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003470 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003471 pgrp = pi->pgrp;
3472 if (pgrp < 0) /* true for 1st process only */
3473 pgrp = getpid();
3474 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003475 /* We do it in *every* child, not just first,
3476 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003477 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003478 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003479 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003480#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00003481 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003482 xmove_fd(pipefds[1], 1); /* write end */
3483 if (pipefds[0] > 1)
3484 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00003485 /* Like bash, explicit redirects override pipes,
3486 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003487 if (setup_redirects(command, NULL))
3488 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00003489
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003490 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003491 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3492
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003493 /* Stores to nommu_save list of env vars putenv'ed
3494 * (NOMMU, on MMU we don't need that) */
3495 /* cast away volatility... */
3496 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003497 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00003498 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003499
Denis Vlasenkof9375282009-04-05 19:13:39 +00003500 /* parent or error */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003501 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003502#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003503 /* Clean up after vforked child */
3504 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003505 free(nommu_save.argv_from_re_execing);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003506 free_strings_and_unsetenv(nommu_save.new_env, 1);
3507 putenv_all(nommu_save.old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003508 /* Free the pointers, but the strings themselves
3509 * are in environ now, don't use free_strings! */
3510 free(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003511#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003512 free(argv_expanded);
3513 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003514 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003515 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003516 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003517 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003518 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003519#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003520 /* Second and next children need to know pid of first one */
3521 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003522 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003523#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003524 }
Eric Andersen25f27032001-04-26 23:22:31 +00003525
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003526 if (i)
3527 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003528 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003529 close(pipefds[1]); /* write end */
3530 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00003531 nextin = pipefds[0];
3532 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003533
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003534 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003535 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00003536 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3537 return 1;
3538 }
3539
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003540 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003541 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003542 return -1;
3543}
3544
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003545#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003546static void debug_print_tree(struct pipe *pi, int lvl)
3547{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003548 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003549 [PIPE_SEQ] = "SEQ",
3550 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003551 [PIPE_OR ] = "OR" ,
3552 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003553 };
3554 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003555 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003556#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003557 [RES_IF ] = "IF" ,
3558 [RES_THEN ] = "THEN" ,
3559 [RES_ELIF ] = "ELIF" ,
3560 [RES_ELSE ] = "ELSE" ,
3561 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003562#endif
3563#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003564 [RES_FOR ] = "FOR" ,
3565 [RES_WHILE] = "WHILE",
3566 [RES_UNTIL] = "UNTIL",
3567 [RES_DO ] = "DO" ,
3568 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003569#endif
3570#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003571 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003572#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003573#if ENABLE_HUSH_CASE
3574 [RES_CASE ] = "CASE" ,
3575 [RES_MATCH] = "MATCH",
3576 [RES_CASEI] = "CASEI",
3577 [RES_ESAC ] = "ESAC" ,
3578#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00003579 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003580 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003581 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003582 static const char *const GRPTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003583 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00003584 "()",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003585#if ENABLE_HUSH_FUNCTIONS
3586 "func()",
3587#endif
3588 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003589
3590 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003591
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003592 pin = 0;
3593 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003594 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3595 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003596 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003597 while (prn < pi->num_cmds) {
3598 struct command *command = &pi->cmds[prn];
3599 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003600
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003601 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003602 lvl*2, "", prn,
3603 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003604 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003605 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003606 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003607 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003608 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003609 prn++;
3610 continue;
3611 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003612 if (argv) while (*argv) {
3613 fprintf(stderr, " '%s'", *argv);
3614 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003615 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003616 fprintf(stderr, "\n");
3617 prn++;
3618 }
3619 pi = pi->next;
3620 pin++;
3621 }
3622}
3623#endif
3624
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003625/* NB: called by pseudo_exec, and therefore must not modify any
3626 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003627static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003628{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003629#if ENABLE_HUSH_CASE
3630 char *case_word = NULL;
3631#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003632#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003633 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003634 char *for_varname = NULL;
3635 char **for_lcur = NULL;
3636 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00003637#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003638 smallint last_followup;
3639 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003640#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003641 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003642#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003643 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003644#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00003645#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003646 smallint rword; /* enum reserved_style */
3647 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003648#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003649
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003650 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003651 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003652
Denis Vlasenko06810332007-05-21 23:30:54 +00003653#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003654 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003655 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3656 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003657 continue;
3658 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003659 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003660 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003661 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003662 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003663 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003664 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003665 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003666 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003667 continue;
3668 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003669 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3670 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003671 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003672 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003673 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003674 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003675 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003676 }
3677 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003678#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003679
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003680 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00003681 * in order to return, no direct "return" statements please.
3682 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003683
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003684#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003685 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003686#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003687
Denis Vlasenko0e151382009-04-06 18:40:31 +00003688#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003689 rword = RES_NONE;
3690 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003691#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003692 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003693 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003694
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003695 /* Go through list of pipes, (maybe) executing them. */
3696 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00003697 if (G.flag_SIGINT)
3698 break;
3699
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003700 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003701 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3702 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00003703#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00003704 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003705 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00003706 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003707 /* start of a loop: remember where loop starts */
3708 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003709 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003710 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003711#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003712 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003713 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003714 if ((rcode == 0 && last_followup == PIPE_OR)
3715 || (rcode != 0 && last_followup == PIPE_AND)
3716 ) {
3717 /* It is "<true> || CMD" or "<false> && CMD"
3718 * and we should not execute CMD */
3719 debug_printf_exec("skipped cmd because of || or &&\n");
3720 last_followup = pi->followup;
3721 continue;
3722 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003723 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003724 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003725 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00003726#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003727 if (cond_code) {
3728 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00003729 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003730 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003731 /* "if <false> THEN cmd": skip cmd */
3732 continue;
3733 }
3734 } else {
3735 if (rword == RES_ELSE || rword == RES_ELIF) {
3736 /* "if <true> then ... ELSE/ELIF cmd":
3737 * skip cmd and all following ones */
3738 break;
3739 }
3740 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003741#endif
3742#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003743 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003744 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003745 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003746
3747 static const char encoded_dollar_at[] ALIGN1 = {
3748 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3749 }; /* encoded representation of "$@" */
3750 static const char *const encoded_dollar_at_argv[] = {
3751 encoded_dollar_at, NULL
3752 }; /* argv list with one element: "$@" */
3753 char **vals;
3754
3755 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003756 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003757 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003758 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003759 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003760 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003761 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003762 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003763 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003764 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003765 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003766 debug_print_strings("for_list made from", vals);
3767 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003768 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003769 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003770 for_varname = pi->cmds[0].argv[0];
3771 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003772 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003773 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003774 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00003775 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003776 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003777 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003778 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003779 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003780 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003781 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003782 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003783 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003784 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3785 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003786 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003787 if (rword == RES_IN) {
3788 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3789 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003790 if (rword == RES_DONE) {
3791 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003792 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003793#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003794#if ENABLE_HUSH_CASE
3795 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003796 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003797 continue;
3798 }
3799 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003800 char **argv;
3801
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003802 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3803 break;
3804 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003805 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003806 while (*argv) {
3807 char *pattern = expand_string_to_string(*argv);
3808 /* TODO: which FNM_xxx flags to use? */
3809 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3810 free(pattern);
3811 if (cond_code == 0) { /* match! we will execute this branch */
3812 free(case_word); /* make future "word)" stop */
3813 case_word = NULL;
3814 break;
3815 }
3816 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003817 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003818 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003819 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003820 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003821 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003822 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003823 }
3824#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003825 /* Just pressing <enter> in shell should check for jobs.
3826 * OTOH, in non-interactive shell this is useless
3827 * and only leads to extra job checks */
3828 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003829 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00003830 goto check_jobs_and_continue;
3831 continue;
3832 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003833
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003834 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00003835 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003836 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003837 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003838 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003839 {
3840 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003841#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00003842 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003843#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003844 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3845 if (r != -1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003846 /* We only ran a builtin: rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003847 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003848 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003849 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003850 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003851#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003852 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003853 if (G.flag_break_continue) {
3854 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003855 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003856 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003857 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003858 G.depth_break_continue--;
3859 if (G.depth_break_continue == 0)
3860 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003861 /* else: e.g. "continue 2" should *break* once, *then* continue */
3862 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003863 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003864 goto check_jobs_and_break;
3865 /* "continue": simulate end of loop */
3866 rword = RES_DONE;
3867 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003868 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003869#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003870 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003871 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003872 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003873 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3874 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003875 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003876#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003877 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003878 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003879#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003880 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003881 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003882 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003883#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003884 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003885 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003886 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003887 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003888 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003889 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003890#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003891 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003892 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003893 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003894 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003895 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003896 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003897 }
3898 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003899
3900 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00003901#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003902 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003903 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00003904#endif
3905#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003906 /* Beware of "while false; true; do ..."! */
3907 if (pi->next && pi->next->res_word == RES_DO) {
3908 if (rword == RES_WHILE) {
3909 if (rcode) {
3910 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003911 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003912 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3913 goto check_jobs_and_break;
3914 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003915 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003916 if (rword == RES_UNTIL) {
3917 if (!rcode) {
3918 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003919 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003920 checkjobs(NULL);
3921 break;
3922 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003923 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003924 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003925#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00003926
3927 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00003928 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003929 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003930
3931#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00003932 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003933#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003934#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003935 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003936 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003937 free(for_list);
3938#endif
3939#if ENABLE_HUSH_CASE
3940 free(case_word);
3941#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003942 debug_leave();
3943 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003944 return rcode;
3945}
3946
Eric Andersen25f27032001-04-26 23:22:31 +00003947/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003948static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003949{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003950 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003951 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003952 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003953 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003954 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003955 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003956 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00003957 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003958 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003959 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003960 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003961 return rcode;
3962}
3963
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003964
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003965static struct pipe *new_pipe(void)
3966{
Eric Andersen25f27032001-04-26 23:22:31 +00003967 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003968 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003969 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003970 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003971 return pi;
3972}
3973
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003974/* Command (member of a pipe) is complete. The only possible error here
3975 * is out of memory, in which case xmalloc exits. */
3976static int done_command(struct parse_context *ctx)
3977{
3978 /* The command is really already in the pipe structure, so
3979 * advance the pipe counter and make a new, null command. */
3980 struct pipe *pi = ctx->pipe;
3981 struct command *command = ctx->command;
3982
3983 if (command) {
3984 if (command->group == NULL
3985 && command->argv == NULL
3986 && command->redirects == NULL
3987 ) {
3988 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003989 memset(command, 0, sizeof(*command)); /* paranoia */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003990 return pi->num_cmds;
3991 }
3992 pi->num_cmds++;
3993 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003994 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003995 } else {
3996 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3997 }
3998
3999 /* Only real trickiness here is that the uncommitted
4000 * command structure is not counted in pi->num_cmds. */
4001 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
4002 command = &pi->cmds[pi->num_cmds];
4003 memset(command, 0, sizeof(*command));
4004
4005 ctx->command = command;
4006 /* but ctx->pipe and ctx->list_head remain unchanged */
4007
4008 return pi->num_cmds; /* used only for 0/nonzero check */
4009}
4010
4011static void done_pipe(struct parse_context *ctx, pipe_style type)
4012{
4013 int not_null;
4014
4015 debug_printf_parse("done_pipe entered, followup %d\n", type);
4016 /* Close previous command */
4017 not_null = done_command(ctx);
4018 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004019#if HAS_KEYWORDS
4020 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4021 ctx->ctx_inverted = 0;
4022 ctx->pipe->res_word = ctx->ctx_res_w;
4023#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004024
4025 /* Without this check, even just <enter> on command line generates
4026 * tree of three NOPs (!). Which is harmless but annoying.
4027 * IOW: it is safe to do it unconditionally.
4028 * RES_NONE case is for "for a in; do ..." (empty IN set)
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004029 * and other cases to work. */
4030 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004031#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004032 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004033#endif
4034#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004035 || ctx->ctx_res_w == RES_DONE
4036 || ctx->ctx_res_w == RES_FOR
4037 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004038#endif
4039#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004040 || ctx->ctx_res_w == RES_ESAC
4041#endif
4042 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004043 struct pipe *new_p;
4044 debug_printf_parse("done_pipe: adding new pipe: "
4045 "not_null:%d ctx->ctx_res_w:%d\n",
4046 not_null, ctx->ctx_res_w);
4047 new_p = new_pipe();
4048 ctx->pipe->next = new_p;
4049 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004050 /* RES_THEN, RES_DO etc are "sticky" -
4051 * they remain set for commands inside if/while.
4052 * This is used to control execution.
4053 * RES_FOR and RES_IN are NOT sticky (needed to support
4054 * cases where variable or value happens to match a keyword):
4055 */
4056#if ENABLE_HUSH_LOOPS
4057 if (ctx->ctx_res_w == RES_FOR
4058 || ctx->ctx_res_w == RES_IN)
4059 ctx->ctx_res_w = RES_NONE;
4060#endif
4061#if ENABLE_HUSH_CASE
4062 if (ctx->ctx_res_w == RES_MATCH)
4063 ctx->ctx_res_w = RES_CASEI;
4064#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004065 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004066 /* Create the memory for command, roughly:
4067 * ctx->pipe->cmds = new struct command;
4068 * ctx->command = &ctx->pipe->cmds[0];
4069 */
4070 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004071 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004072 }
4073 debug_printf_parse("done_pipe return\n");
4074}
4075
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004076static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004077{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004078 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004079 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004080 /* Create the memory for command, roughly:
4081 * ctx->pipe->cmds = new struct command;
4082 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004083 */
4084 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004085}
4086
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004087/* If a reserved word is found and processed, parse context is modified
4088 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004089 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004090#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004091struct reserved_combo {
4092 char literal[6];
4093 unsigned char res;
4094 unsigned char assignment_flag;
4095 int flag;
4096};
4097enum {
4098 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004099#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004100 FLAG_IF = (1 << RES_IF ),
4101 FLAG_THEN = (1 << RES_THEN ),
4102 FLAG_ELIF = (1 << RES_ELIF ),
4103 FLAG_ELSE = (1 << RES_ELSE ),
4104 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004105#endif
4106#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004107 FLAG_FOR = (1 << RES_FOR ),
4108 FLAG_WHILE = (1 << RES_WHILE),
4109 FLAG_UNTIL = (1 << RES_UNTIL),
4110 FLAG_DO = (1 << RES_DO ),
4111 FLAG_DONE = (1 << RES_DONE ),
4112 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004113#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004114#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004115 FLAG_MATCH = (1 << RES_MATCH),
4116 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004117#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004118 FLAG_START = (1 << RES_XXXX ),
4119};
4120
4121static const struct reserved_combo* match_reserved_word(o_string *word)
4122{
Eric Andersen25f27032001-04-26 23:22:31 +00004123 /* Mostly a list of accepted follow-up reserved words.
4124 * FLAG_END means we are done with the sequence, and are ready
4125 * to turn the compound list into a command.
4126 * FLAG_START means the word must start a new compound list.
4127 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004128 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004129#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004130 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4131 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4132 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4133 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4134 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4135 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004136#endif
4137#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004138 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4139 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4140 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4141 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4142 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4143 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004144#endif
4145#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004146 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4147 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004148#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004149 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004150 const struct reserved_combo *r;
4151
4152 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4153 if (strcmp(word->data, r->literal) == 0)
4154 return r;
4155 }
4156 return NULL;
4157}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004158/* Return 0: not a keyword, 1: keyword
4159 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004160static int reserved_word(o_string *word, struct parse_context *ctx)
4161{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004162#if ENABLE_HUSH_CASE
4163 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004164 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004165 };
4166#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004167 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004168
Denis Vlasenkobb929512009-04-16 10:59:40 +00004169 if (word->o_quoted)
4170 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004171 r = match_reserved_word(word);
4172 if (!r)
4173 return 0;
4174
4175 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004176#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004177 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
4178 /* "case word IN ..." - IN part starts first match part */
4179 r = &reserved_match;
4180 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004181#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004182 if (r->flag == 0) { /* '!' */
4183 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004184 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004185 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004186 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004187 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004188 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004189 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004190 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004191 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004192
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004193 old = xmalloc(sizeof(*old));
4194 debug_printf_parse("push stack %p\n", old);
4195 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004196 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004197 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004198 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004199 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004200 ctx->ctx_res_w = RES_SNTX;
4201 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004202 } else {
4203 /* "{...} fi" is ok. "{...} if" is not
4204 * Example:
4205 * if { echo foo; } then { echo bar; } fi */
4206 if (ctx->command->group)
4207 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004208 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004209
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004210 ctx->ctx_res_w = r->res;
4211 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004212 word->o_assignment = r->assignment_flag;
4213
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004214 if (ctx->old_flag & FLAG_END) {
4215 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004216
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004217 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004218 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004219 old = ctx->stack;
4220 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004221 old->command->grp_type = GRP_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004222#if !BB_MMU
4223 o_addstr(&old->as_string, ctx->as_string.data);
4224 o_free_unsafe(&ctx->as_string);
4225 old->command->group_as_string = xstrdup(old->as_string.data);
4226 debug_printf_parse("pop, remembering as:'%s'\n",
4227 old->command->group_as_string);
4228#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004229 *ctx = *old; /* physical copy */
4230 free(old);
4231 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004232 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004233}
Denis Vlasenko06810332007-05-21 23:30:54 +00004234#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004235
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004236/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004237 * Normal return is 0. Syntax errors return 1.
4238 * Note: on return, word is reset, but not o_free'd!
4239 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004240static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004241{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004242 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004243
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004244 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004245 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004246 debug_printf_parse("done_word return 0: true null, ignored\n");
4247 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004248 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004249
Eric Andersen25f27032001-04-26 23:22:31 +00004250 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004251 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4252 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004253 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4254 * "2.7 Redirection
4255 * ...the word that follows the redirection operator
4256 * shall be subjected to tilde expansion, parameter expansion,
4257 * command substitution, arithmetic expansion, and quote
4258 * removal. Pathname expansion shall not be performed
4259 * on the word by a non-interactive shell; an interactive
4260 * shell may perform it, but shall do so only when
4261 * the expansion would result in one word."
4262 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004263 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004264 /* Cater for >\file case:
4265 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4266 * Same with heredocs:
4267 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4268 */
4269 unbackslash(ctx->pending_redirect->rd_filename);
4270 /* Is it <<"HEREDOC"? */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004271 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4272 && word->o_quoted
4273 ) {
4274 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4275 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004276 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004277 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004278 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004279 /* If this word wasn't an assignment, next ones definitely
4280 * can't be assignments. Even if they look like ones. */
4281 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4282 && word->o_assignment != WORD_IS_KEYWORD
4283 ) {
4284 word->o_assignment = NOT_ASSIGNMENT;
4285 } else {
4286 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4287 command->assignment_cnt++;
4288 word->o_assignment = MAYBE_ASSIGNMENT;
4289 }
4290
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004291#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004292# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004293 if (ctx->ctx_dsemicolon
4294 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4295 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004296 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004297 /* ctx->ctx_res_w = RES_MATCH; */
4298 ctx->ctx_dsemicolon = 0;
4299 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004300# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004301 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004302# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004303 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4304 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004305# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004306 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004307 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
4308 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004309 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004310 debug_printf_parse("done_word return %d\n",
4311 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004312 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004313 }
Eric Andersen25f27032001-04-26 23:22:31 +00004314 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004315#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004316 if (command->group) {
4317 /* "{ echo foo; } echo bar" - bad */
4318 syntax_error_at(word->data);
4319 debug_printf_parse("done_word return 1: syntax error, "
4320 "groups and arglists don't mix\n");
4321 return 1;
4322 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004323 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004324 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4325 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004326 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004327 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004328 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004329 char *p = word->data;
4330 while (p[0] == SPECIAL_VAR_SYMBOL
4331 && (p[1] & 0x7f) == '@'
4332 && p[2] == SPECIAL_VAR_SYMBOL
4333 ) {
4334 p += 3;
4335 }
4336 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004337 /* saw no "$@", or not only "$@" but some
4338 * real text is there too */
4339 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004340 * e.g. "", $empty"" etc to not disappear */
4341 o_addchr(word, SPECIAL_VAR_SYMBOL);
4342 o_addchr(word, SPECIAL_VAR_SYMBOL);
4343 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004344 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004345 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004346//SEGV, but good idea.
4347// command->argv = add_string_to_strings(command->argv, word->data);
4348// word->data = NULL;
4349// word->length = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004350 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004351 }
Eric Andersen25f27032001-04-26 23:22:31 +00004352
Denis Vlasenko06810332007-05-21 23:30:54 +00004353#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004354 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004355 if (word->o_quoted
4356 || !is_well_formed_var_name(command->argv[0], '\0')
4357 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004358 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004359 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004360 return 1;
4361 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004362 /* Force FOR to have just one word (variable name) */
4363 /* NB: basically, this makes hush see "for v in ..."
4364 * syntax as if it is "for v; in ...". FOR and IN become
4365 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004366 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004367 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004368#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004369#if ENABLE_HUSH_CASE
4370 /* Force CASE to have just one word */
4371 if (ctx->ctx_res_w == RES_CASE) {
4372 done_pipe(ctx, PIPE_SEQ);
4373 }
4374#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004375
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004376 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004377
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004378 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004379 return 0;
4380}
4381
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004382
4383/* Peek ahead in the input to find out if we have a "&n" construct,
4384 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004385 * Return:
4386 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4387 * REDIRFD_SYNTAX_ERR if syntax error,
4388 * REDIRFD_TO_FILE if no & was seen,
4389 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004390 */
4391#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004392#define parse_redir_right_fd(as_string, input) \
4393 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004394#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004395static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004396{
4397 int ch, d, ok;
4398
4399 ch = i_peek(input);
4400 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004401 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004402
4403 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004404 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004405 ch = i_peek(input);
4406 if (ch == '-') {
4407 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004408 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004409 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004410 }
4411 d = 0;
4412 ok = 0;
4413 while (ch != EOF && isdigit(ch)) {
4414 d = d*10 + (ch-'0');
4415 ok = 1;
4416 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004417 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004418 ch = i_peek(input);
4419 }
4420 if (ok) return d;
4421
4422//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4423
4424 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004425 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004426}
4427
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004428/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004429 */
4430static int parse_redirect(struct parse_context *ctx,
4431 int fd,
4432 redir_type style,
4433 struct in_str *input)
4434{
4435 struct command *command = ctx->command;
4436 struct redir_struct *redir;
4437 struct redir_struct **redirp;
4438 int dup_num;
4439
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004440 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004441 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004442 /* Check for a '>&1' type redirect */
4443 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4444 if (dup_num == REDIRFD_SYNTAX_ERR)
4445 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004446 } else {
4447 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004448 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004449 if (dup_num) { /* <<-... */
4450 ch = i_getch(input);
4451 nommu_addchr(&ctx->as_string, ch);
4452 ch = i_peek(input);
4453 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004454 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004455
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004456 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004457 int ch = i_peek(input);
4458 if (ch == '|') {
4459 /* >|FILE redirect ("clobbering" >).
4460 * Since we do not support "set -o noclobber" yet,
4461 * >| and > are the same for now. Just eat |.
4462 */
4463 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004464 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004465 }
4466 }
4467
4468 /* Create a new redir_struct and append it to the linked list */
4469 redirp = &command->redirects;
4470 while ((redir = *redirp) != NULL) {
4471 redirp = &(redir->next);
4472 }
4473 *redirp = redir = xzalloc(sizeof(*redir));
4474 /* redir->next = NULL; */
4475 /* redir->rd_filename = NULL; */
4476 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004477 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004478
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004479 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4480 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004481
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004482 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004483 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004484 /* Erik had a check here that the file descriptor in question
4485 * is legit; I postpone that to "run time"
4486 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004487 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4488 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004489 } else {
4490 /* Set ctx->pending_redirect, so we know what to do at the
4491 * end of the next parsed word. */
4492 ctx->pending_redirect = redir;
4493 }
4494 return 0;
4495}
4496
Eric Andersen25f27032001-04-26 23:22:31 +00004497/* If a redirect is immediately preceded by a number, that number is
4498 * supposed to tell which file descriptor to redirect. This routine
4499 * looks for such preceding numbers. In an ideal world this routine
4500 * needs to handle all the following classes of redirects...
4501 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4502 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4503 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4504 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004505 *
4506 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4507 * "2.7 Redirection
4508 * ... If n is quoted, the number shall not be recognized as part of
4509 * the redirection expression. For example:
4510 * echo \2>a
4511 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004512 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004513 *
4514 * A -1 return means no valid number was found,
4515 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004516 */
4517static int redirect_opt_num(o_string *o)
4518{
4519 int num;
4520
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004521 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004522 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004523 num = bb_strtou(o->data, NULL, 10);
4524 if (errno || num < 0)
4525 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004526 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004527 return num;
4528}
4529
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004530#if BB_MMU
4531#define fetch_till_str(as_string, input, word, skip_tabs) \
4532 fetch_till_str(input, word, skip_tabs)
4533#endif
4534static char *fetch_till_str(o_string *as_string,
4535 struct in_str *input,
4536 const char *word,
4537 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004538{
4539 o_string heredoc = NULL_O_STRING;
4540 int past_EOL = 0;
4541 int ch;
4542
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004543 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004544 while (1) {
4545 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004546 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004547 if (ch == '\n') {
4548 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4549 heredoc.data[past_EOL] = '\0';
4550 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4551 return heredoc.data;
4552 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004553 do {
4554 o_addchr(&heredoc, ch);
4555 past_EOL = heredoc.length;
4556 jump_in:
4557 do {
4558 ch = i_getch(input);
4559 nommu_addchr(as_string, ch);
4560 } while (skip_tabs && ch == '\t');
4561 } while (ch == '\n');
4562 }
4563 if (ch == EOF) {
4564 o_free_unsafe(&heredoc);
4565 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004566 }
4567 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004568 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004569 }
4570}
4571
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004572/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4573 * and load them all. There should be exactly heredoc_cnt of them.
4574 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004575static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4576{
4577 struct pipe *pi = ctx->list_head;
4578
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004579 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004580 int i;
4581 struct command *cmd = pi->cmds;
4582
4583 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4584 pi->num_cmds,
4585 cmd->argv ? cmd->argv[0] : "NONE");
4586 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004587 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004588
4589 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4590 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004591 while (redir) {
4592 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004593 char *p;
4594
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004595 redir->rd_type = REDIRECT_HEREDOC2;
4596 /* redir->dup is (ab)used to indicate <<- */
4597 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004598 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004599 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004600 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004601 return 1;
4602 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004603 free(redir->rd_filename);
4604 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004605 heredoc_cnt--;
4606 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004607 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004608 }
4609 cmd++;
4610 }
4611 pi = pi->next;
4612 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004613#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004614 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004615 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004616 bb_error_msg_and_die("heredoc BUG 2");
4617#endif
4618 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004619}
4620
4621
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004622#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004623static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004624{
4625 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004626 int pid, channel[2];
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004627#if !BB_MMU
4628 char **to_free;
4629#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004630
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00004631 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00004632 pid = BB_MMU ? fork() : vfork();
4633 if (pid < 0)
4634 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004635
Denis Vlasenko05743d72008-02-10 12:10:08 +00004636 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004637 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004638 /* Process substitution is not considered to be usual
4639 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004640 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4641 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00004642 bb_signals(0
4643 + (1 << SIGTSTP)
4644 + (1 << SIGTTIN)
4645 + (1 << SIGTTOU)
4646 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004647 close(channel[0]); /* NB: close _first_, then move fd! */
4648 xmove_fd(channel[1], 1);
4649 /* Prevent it from trying to handle ctrl-z etc */
4650 USE_HUSH_JOB(G.run_list_level = 1;)
4651#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004652 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004653 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004654 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004655#else
4656 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00004657 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4658 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004659 * echo OK
4660 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004661 re_execute_shell(&to_free,
4662 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004663 G.global_argv[0],
4664 G.global_argv + 1);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004665#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004666 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004667
4668 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004669 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004670#if !BB_MMU
4671 free(to_free);
4672#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004673 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004674 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00004675 return pf;
4676}
4677
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004678/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004679static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004680{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004681 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004682 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004683 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004684
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004685 pf = generate_stream_from_string(s);
4686 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00004687 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004688 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00004689
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004690 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004691 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004692 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004693 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004694 if (ch == '\n') {
4695 eol_cnt++;
4696 continue;
4697 }
4698 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004699 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004700 eol_cnt--;
4701 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004702 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004703 }
4704
4705 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004706 /* Note: we got EOF, and we just close the read end of the pipe.
4707 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004708 * Try these:
4709 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4710 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004711 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004712 fclose(pf);
4713 debug_printf("closed FILE from child. return 0\n");
4714 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004715}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004716#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004717
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004718static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004719 struct in_str *input, int ch)
4720{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004721 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004722 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004723 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004724 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004725 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004726 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004727
4728 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004729#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004730 if (ch == '(' && !dest->o_quoted) {
4731 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004732 if (done_word(dest, ctx))
4733 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004734 if (!command->argv)
4735 goto skip; /* (... */
4736 if (command->argv[1]) { /* word word ... (... */
4737 syntax_error_unexpected_ch('(');
4738 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004739 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004740 /* it is "word(..." or "word (..." */
4741 do
4742 ch = i_getch(input);
4743 while (ch == ' ' || ch == '\t');
4744 if (ch != ')') {
4745 syntax_error_unexpected_ch(ch);
4746 return 1;
4747 }
4748 nommu_addchr(&ctx->as_string, ch);
4749 do
4750 ch = i_getch(input);
4751 while (ch == ' ' || ch == '\t' || ch == '\n');
4752 if (ch != '{') {
4753 syntax_error_unexpected_ch(ch);
4754 return 1;
4755 }
4756 nommu_addchr(&ctx->as_string, ch);
4757 command->grp_type = GRP_FUNCTION;
4758 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004759 }
4760#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004761 if (command->argv /* word [word]{... */
4762 || dest->length /* word{... */
4763 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004764 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004765 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004766 debug_printf_parse("parse_group return 1: "
4767 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004768 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004769 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004770
4771#if ENABLE_HUSH_FUNCTIONS
4772 skip:
4773#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004774 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004775 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004776 endch = ')';
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004777 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00004778 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004779
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004780 {
4781#if !BB_MMU
4782 char *as_string = NULL;
4783#endif
4784 pipe_list = parse_stream(&as_string, input, endch);
4785#if !BB_MMU
4786 if (as_string)
4787 o_addstr(&ctx->as_string, as_string);
4788#endif
4789 /* empty ()/{} or parse error? */
4790 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004791 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004792#if !BB_MMU
4793 free(as_string);
4794#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004795 debug_printf_parse("parse_group return 1: "
4796 "parse_stream returned %p\n", pipe_list);
4797 return 1;
4798 }
4799 command->group = pipe_list;
4800#if !BB_MMU
4801 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4802 command->group_as_string = as_string;
4803 debug_printf_parse("end of group, remembering as:'%s'\n",
4804 command->group_as_string);
4805#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004806 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004807 debug_printf_parse("parse_group return 0\n");
4808 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004809 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004810}
4811
Mike Frysinger98c52642009-04-02 10:02:37 +00004812#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004813/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004814static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004815/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004816static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004817{
4818 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004819 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004820 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004821 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004822 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004823 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004824 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004825 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004826 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004827 }
4828}
4829/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004830static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004831{
4832 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004833 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004834 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004835 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004836 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004837 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004838 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004839 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004840 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004841 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004842 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004843 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004844 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004845 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004846 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004847 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004848 continue;
4849 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004850 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004851 }
4852}
4853/* Process `cmd` - copy contents until "`" is seen. Complicated by
4854 * \` quoting.
4855 * "Within the backquoted style of command substitution, backslash
4856 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4857 * The search for the matching backquote shall be satisfied by the first
4858 * backquote found without a preceding backslash; during this search,
4859 * if a non-escaped backquote is encountered within a shell comment,
4860 * a here-document, an embedded command substitution of the $(command)
4861 * form, or a quoted string, undefined results occur. A single-quoted
4862 * or double-quoted string that begins, but does not end, within the
4863 * "`...`" sequence produces undefined results."
4864 * Example Output
4865 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4866 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004867static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004868{
4869 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004870 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004871 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004872 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004873 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004874 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004875 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004876 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004877 if (ch == '\\') {
4878 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004879 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004880 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004881 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004882 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004883 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004884 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004885 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004886 ch = ch2;
4887 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004888 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004889 }
4890}
4891/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4892 * quoting and nested ()s.
4893 * "With the $(command) style of command substitution, all characters
4894 * following the open parenthesis to the matching closing parenthesis
4895 * constitute the command. Any valid shell script can be used for command,
4896 * except a script consisting solely of redirections which produces
4897 * unspecified results."
4898 * Example Output
4899 * echo $(echo '(TEST)' BEST) (TEST) BEST
4900 * echo $(echo 'TEST)' BEST) TEST) BEST
4901 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4902 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004903static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004904{
4905 int count = 0;
4906 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004907 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004908 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004909 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004910 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004911 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004912 if (ch == '(')
4913 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004914 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00004915 if (--count < 0) {
4916 if (!dbl)
4917 break;
4918 if (i_peek(input) == ')') {
4919 i_getch(input);
4920 break;
4921 }
4922 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004923 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004924 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004925 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004926 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004927 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004928 continue;
4929 }
4930 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004931 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004932 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004933 continue;
4934 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004935 if (ch == '\\') {
4936 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004937 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004938 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004939 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004940 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004941 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004942 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004943 continue;
4944 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004945 }
4946}
Mike Frysinger98c52642009-04-02 10:02:37 +00004947#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004948
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004949/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004950#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004951#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004952 handle_dollar(dest, input)
4953#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004954static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004955 o_string *dest,
4956 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00004957{
Mike Frysinger6379bb42009-03-28 18:55:03 +00004958 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004959 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004960 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004961
4962 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004963 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004964 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004965 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004966 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004967 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004968 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004969 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004970 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004971 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004972 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004973 if (!isalnum(ch) && ch != '_')
4974 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004975 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004976 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004977 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004978 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004979 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004980 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004981 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004982 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004983 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004984 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004985 o_addchr(dest, ch | quote_mask);
4986 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004987 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004988 case '$': /* pid */
4989 case '!': /* last bg pid */
4990 case '?': /* last exit code */
4991 case '#': /* number of args */
4992 case '*': /* args */
4993 case '@': /* args */
4994 goto make_one_char_var;
4995 case '{': {
4996 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00004997
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004998 o_addchr(dest, SPECIAL_VAR_SYMBOL);
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);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005001 /* XXX maybe someone will try to escape the '}' */
5002 expansion = 0;
5003 first_char = true;
5004 all_digits = false;
5005 while (1) {
5006 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005007 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005008 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00005009 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00005010
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005011 if (first_char) {
5012 if (ch == '#')
5013 /* ${#var}: length of var contents */
5014 goto char_ok;
5015 else if (isdigit(ch)) {
5016 all_digits = true;
5017 goto char_ok;
5018 }
5019 }
5020
5021 if (expansion < 2
5022 && ( (all_digits && !isdigit(ch))
5023 || (!all_digits && !isalnum(ch) && ch != '_')
5024 )
5025 ) {
5026 /* handle parameter expansions
5027 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5028 */
5029 if (first_char)
5030 goto case_default;
5031 switch (ch) {
5032 case ':': /* null modifier */
5033 if (expansion == 0) {
5034 debug_printf_parse(": null modifier\n");
5035 ++expansion;
5036 break;
5037 }
5038 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005039 case '#': /* remove prefix */
5040 case '%': /* remove suffix */
5041 if (expansion == 0) {
5042 debug_printf_parse(": remove suffix/prefix\n");
5043 expansion = 2;
5044 break;
5045 }
5046 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005047 case '-': /* default value */
5048 case '=': /* assign default */
5049 case '+': /* alternative */
5050 case '?': /* error indicate */
5051 debug_printf_parse(": parameter expansion\n");
5052 expansion = 2;
5053 break;
5054 default:
5055 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005056 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005057 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5058 return 1;
5059 }
5060 }
5061 char_ok:
5062 debug_printf_parse(": '%c'\n", ch);
5063 o_addchr(dest, ch | quote_mask);
5064 quote_mask = 0;
5065 first_char = false;
5066 }
5067 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5068 break;
5069 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005070#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005071 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005072# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005073 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005074# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005075 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005076 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005077# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005078 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005079 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005080 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005081 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5082 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005083# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005084 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005085# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005086 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005087# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005088 if (as_string) {
5089 o_addstr(as_string, dest->data + pos);
5090 o_addchr(as_string, ')');
5091 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005092 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005093# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005094 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005095 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005096 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005097# endif
5098# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005099 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5100 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005101# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005102 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005103# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005104 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005105# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005106 if (as_string) {
5107 o_addstr(as_string, dest->data + pos);
5108 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005109 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005110# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005111 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005112# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005113 break;
5114 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005115#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005116 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005117 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005118 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005119 ch = i_peek(input);
5120 if (isalnum(ch)) { /* it's $_name or $_123 */
5121 ch = '_';
5122 goto make_var;
5123 }
5124 /* else: it's $_ */
5125 /* TODO: */
5126 /* $_ Shell or shell script name; or last cmd name */
5127 /* $- Option flags set by set builtin or shell options (-i etc) */
5128 default:
5129 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005130 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005131 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005132 return 0;
5133}
5134
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005135#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005136#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005137 parse_stream_dquoted(dest, input, dquote_end)
5138#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005139static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005140 o_string *dest,
5141 struct in_str *input,
5142 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005143{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005144 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005145 int next;
5146
5147 again:
5148 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005149 if (ch != EOF)
5150 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005151 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005152 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005153 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005154 debug_printf_parse("parse_stream_dquoted return 0\n");
5155 return 0;
5156 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005157 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005158 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005159 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005160 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005161 }
5162 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005163 if (ch != '\n') {
5164 next = i_peek(input);
5165 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005166 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5167 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005168 if (ch == '\\') {
5169 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005170 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005171 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005172 }
5173 /* bash:
5174 * "The backslash retains its special meaning [in "..."]
5175 * only when followed by one of the following characters:
5176 * $, `, ", \, or <newline>. A double quote may be quoted
5177 * within double quotes by preceding it with a backslash.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005178 */
5179 if (strchr("$`\"\\", next) != NULL) {
5180 o_addqchr(dest, i_getch(input));
5181 } else {
5182 o_addqchr(dest, '\\');
5183 }
5184 goto again;
5185 }
5186 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005187 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005188 debug_printf_parse("parse_stream_dquoted return 1: "
5189 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005190 return 1;
5191 }
5192 goto again;
5193 }
5194#if ENABLE_HUSH_TICK
5195 if (ch == '`') {
5196 //int pos = dest->length;
5197 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5198 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005199 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005200 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5201 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005202 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005203 }
5204#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005205 o_addQchr(dest, ch);
5206 if (ch == '='
5207 && (dest->o_assignment == MAYBE_ASSIGNMENT
5208 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005209 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005210 ) {
5211 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5212 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005213 goto again;
5214}
5215
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005216/*
5217 * Scan input until EOF or end_trigger char.
5218 * Return a list of pipes to execute, or NULL on EOF
5219 * or if end_trigger character is met.
5220 * On syntax error, exit is shell is not interactive,
5221 * reset parsing machinery and start parsing anew,
5222 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005223 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005224static struct pipe *parse_stream(char **pstring,
5225 struct in_str *input,
5226 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005227{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005228 struct parse_context ctx;
5229 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005230 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005231 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005232
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005233 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005234 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005235 * found. When recursing, quote state is passed in via dest->o_escape.
5236 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005237 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5238 end_trigger ? : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005239 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005240
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005241 G.ifs = get_local_var_value("IFS");
5242 if (G.ifs == NULL)
5243 G.ifs = " \t\n";
5244
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005245 reset:
5246#if ENABLE_HUSH_INTERACTIVE
5247 input->promptmode = 0; /* PS1 */
5248#endif
5249 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5250 initialize_context(&ctx);
5251 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005252 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005253 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005254 const char *is_ifs;
5255 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005256 int ch;
5257 int next;
5258 int redir_fd;
5259 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005260
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005261 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005262 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005263 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005264 goto parse_error;
5265 }
5266 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005267 is_in_dquote = 0;
5268 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005269 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005270 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5271 ch, ch, dest.o_escape);
5272 if (ch == EOF) {
5273 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005274
5275 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005276 syntax_error_unterm_str("here document");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005277 xfunc_die();
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005278 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005279 if (done_word(&dest, &ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005280 xfunc_die();
Denis Vlasenko55789c62008-06-18 16:30:42 +00005281 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005282 o_free(&dest);
5283 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005284 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005285 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005286 /* (this makes bare "&" cmd a no-op.
5287 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005288 if (pi->num_cmds == 0
5289 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5290 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005291 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005292 pi = NULL;
5293 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005294#if !BB_MMU
5295 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5296 if (pstring)
5297 *pstring = ctx.as_string.data;
5298 else
5299 o_free_unsafe(&ctx.as_string);
5300#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005301 debug_leave();
5302 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005303 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005304 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005305 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005306 is_ifs = strchr(G.ifs, ch);
5307 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5308 "\\$\"" USE_HUSH_TICK("`") /* always special */
5309 , ch);
5310
5311 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005312 o_addQchr(&dest, ch);
5313 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5314 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005315 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005316 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005317 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005318 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005319 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005320 continue;
5321 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005322
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005323 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005324 if (done_word(&dest, &ctx)) {
5325 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005326 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005327 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005328#if ENABLE_HUSH_CASE
5329 /* "case ... in <newline> word) ..." -
5330 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005331 if (ctx.command->argv == NULL
5332 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005333 ) {
5334 continue;
5335 }
5336#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005337 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005338 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005339 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5340 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005341 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005342 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005343 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005344 heredoc_cnt = 0;
5345 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005346 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005347 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005348 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005349 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005350 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005351 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005352 if (end_trigger && end_trigger == ch
5353 && (heredoc_cnt == 0 || end_trigger != ';')
5354 ) {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005355//TODO: disallow "{ cmd }" without semicolon
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005356 if (heredoc_cnt) {
5357 /* This is technically valid:
5358 * { cat <<HERE; }; echo Ok
5359 * heredoc
5360 * heredoc
5361 * heredoc
5362 * HERE
5363 * but we don't support this.
5364 * We require heredoc to be in enclosing {}/(),
5365 * if any.
5366 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005367 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005368 goto parse_error;
5369 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005370 if (done_word(&dest, &ctx)) {
5371 goto parse_error;
5372 }
5373 done_pipe(&ctx, PIPE_SEQ);
5374 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005375 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005376 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005377 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005378 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005379 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005380#if !BB_MMU
5381 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5382 if (pstring)
5383 *pstring = ctx.as_string.data;
5384 else
5385 o_free_unsafe(&ctx.as_string);
5386#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005387 debug_leave();
5388 debug_printf_parse("parse_stream return %p: "
5389 "end_trigger char found\n",
5390 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005391 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005392 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005393 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005394 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005395 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005396
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005397 next = '\0';
5398 if (ch != '\n') {
5399 next = i_peek(input);
5400 }
5401
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005402 /* Catch <, > before deciding whether this word is
5403 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5404 switch (ch) {
5405 case '>':
5406 redir_fd = redirect_opt_num(&dest);
5407 if (done_word(&dest, &ctx)) {
5408 goto parse_error;
5409 }
5410 redir_style = REDIRECT_OVERWRITE;
5411 if (next == '>') {
5412 redir_style = REDIRECT_APPEND;
5413 ch = i_getch(input);
5414 nommu_addchr(&ctx.as_string, ch);
5415 }
5416#if 0
5417 else if (next == '(') {
5418 syntax_error(">(process) not supported");
5419 goto parse_error;
5420 }
5421#endif
5422 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5423 goto parse_error;
5424 continue; /* back to top of while (1) */
5425 case '<':
5426 redir_fd = redirect_opt_num(&dest);
5427 if (done_word(&dest, &ctx)) {
5428 goto parse_error;
5429 }
5430 redir_style = REDIRECT_INPUT;
5431 if (next == '<') {
5432 redir_style = REDIRECT_HEREDOC;
5433 heredoc_cnt++;
5434 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5435 ch = i_getch(input);
5436 nommu_addchr(&ctx.as_string, ch);
5437 } else if (next == '>') {
5438 redir_style = REDIRECT_IO;
5439 ch = i_getch(input);
5440 nommu_addchr(&ctx.as_string, ch);
5441 }
5442#if 0
5443 else if (next == '(') {
5444 syntax_error("<(process) not supported");
5445 goto parse_error;
5446 }
5447#endif
5448 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5449 goto parse_error;
5450 continue; /* back to top of while (1) */
5451 }
5452
5453 if (dest.o_assignment == MAYBE_ASSIGNMENT
5454 /* check that we are not in word in "a=1 2>word b=1": */
5455 && !ctx.pending_redirect
5456 ) {
5457 /* ch is a special char and thus this word
5458 * cannot be an assignment */
5459 dest.o_assignment = NOT_ASSIGNMENT;
5460 }
5461
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005462 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00005463 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005464 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005465 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005466 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005467 if (ch == EOF || ch == '\n')
5468 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005469 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005470 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005471 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005472 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00005473 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005474 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005475 }
5476 break;
5477 case '\\':
5478 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005479 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005480 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005481 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005482 o_addchr(&dest, '\\');
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005483 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005484 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005485 o_addchr(&dest, ch);
5486 /* Example: echo Hello \2>file
5487 * we need to know that word 2 is quoted */
5488 dest.o_quoted = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005489 break;
5490 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005491 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005492 debug_printf_parse("parse_stream parse error: "
5493 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005494 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005495 }
Eric Andersen25f27032001-04-26 23:22:31 +00005496 break;
5497 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005498 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005499 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005500 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005501 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005502 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005503 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005504 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005505 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005506 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005507 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005508 if (dest.o_assignment == NOT_ASSIGNMENT)
5509 o_addqchr(&dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005510 else
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005511 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005512 }
Eric Andersen25f27032001-04-26 23:22:31 +00005513 break;
5514 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005515 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005516 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005517 if (dest.o_assignment == NOT_ASSIGNMENT)
5518 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005519 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005520#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005521 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005522#if !BB_MMU
5523 int pos;
5524#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005525 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5526 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005527#if !BB_MMU
5528 pos = dest.length;
5529#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005530 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005531#if !BB_MMU
5532 o_addstr(&ctx.as_string, dest.data + pos);
5533 o_addchr(&ctx.as_string, '`');
5534#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005535 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5536 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005537 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005538 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005539#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005540 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005541#if ENABLE_HUSH_CASE
5542 case_semi:
5543#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005544 if (done_word(&dest, &ctx)) {
5545 goto parse_error;
5546 }
5547 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005548#if ENABLE_HUSH_CASE
5549 /* Eat multiple semicolons, detect
5550 * whether it means something special */
5551 while (1) {
5552 ch = i_peek(input);
5553 if (ch != ';')
5554 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005555 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005556 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005557 if (ctx.ctx_res_w == RES_CASEI) {
5558 ctx.ctx_dsemicolon = 1;
5559 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005560 break;
5561 }
5562 }
5563#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005564 new_cmd:
5565 /* We just finished a cmd. New one may start
5566 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005567 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00005568 break;
5569 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005570 if (done_word(&dest, &ctx)) {
5571 goto parse_error;
5572 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005573 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005574 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005575 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005576 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005577 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005578 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005579 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005580 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005581 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005582 if (done_word(&dest, &ctx)) {
5583 goto parse_error;
5584 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005585#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005586 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005587 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005588#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005589 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005590 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005591 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005592 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005593 } else {
5594 /* we could pick up a file descriptor choice here
5595 * with redirect_opt_num(), but bash doesn't do it.
5596 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005597 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005598 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005599 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005600 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005601#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005602 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005603 if (ctx.ctx_res_w == RES_MATCH
5604 && ctx.command->argv == NULL /* not (word|(... */
5605 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005606 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005607 ) {
5608 continue;
5609 }
5610#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005611 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005612 if (parse_group(&dest, &ctx, input, ch) != 0) {
5613 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005614 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005615 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005616 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005617#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005618 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005619 goto case_semi;
5620#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005621 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005622 /* proper use of this character is caught by end_trigger:
5623 * if we see {, we call parse_group(..., end_trigger='}')
5624 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005625 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005626 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005627 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005628 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005629 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005630 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005631 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005632
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005633 parse_error:
5634 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005635 struct parse_context *pctx;
5636 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005637
5638 /* Clean up allocated tree.
5639 * Samples for finding leaks on syntax error recovery path.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005640 * Run them from interactive shell, watch pmap `pidof hush`.
5641 * while if false; then false; fi do break; done
5642 * (bash accepts it)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005643 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005644 * Samples to catch leaks at execution:
5645 * while if (true | {true;}); then echo ok; fi; do break; done
5646 * 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 +00005647 */
5648 pctx = &ctx;
5649 do {
5650 /* Update pipe/command counts,
5651 * otherwise freeing may miss some */
5652 done_pipe(pctx, PIPE_SEQ);
5653 debug_printf_clean("freeing list %p from ctx %p\n",
5654 pctx->list_head, pctx);
5655 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005656 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005657 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005658#if !BB_MMU
5659 o_free_unsafe(&pctx->as_string);
5660#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005661 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005662 if (pctx != &ctx) {
5663 free(pctx);
5664 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005665 IF_HAS_KEYWORDS(pctx = p2;)
5666 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005667 /* Free text, clear all dest fields */
5668 o_free(&dest);
5669 /* If we are not in top-level parse, we return,
5670 * our caller will propagate error.
5671 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005672 if (end_trigger != ';') {
5673#if !BB_MMU
5674 if (pstring)
5675 *pstring = NULL;
5676#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005677 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005678 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005679 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005680 /* Discard cached input, force prompt */
5681 input->p = NULL;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005682 USE_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005683 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005684 }
Eric Andersen25f27032001-04-26 23:22:31 +00005685}
5686
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005687/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005688 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5689 * end_trigger controls how often we stop parsing
5690 * NUL: parse all, execute, return
5691 * ';': parse till ';' or newline, execute, repeat till EOF
5692 */
5693static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005694{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005695 while (1) {
5696 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005697
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005698 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005699 if (!pipe_list) /* EOF */
5700 break;
5701 debug_print_tree(pipe_list, 0);
5702 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5703 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005704 }
Eric Andersen25f27032001-04-26 23:22:31 +00005705}
5706
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005707static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005708{
5709 struct in_str input;
5710 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005711 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005712}
5713
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005714static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005715{
Eric Andersen25f27032001-04-26 23:22:31 +00005716 struct in_str input;
5717 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005718 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005719}
5720
Denis Vlasenkof9375282009-04-05 19:13:39 +00005721/* Called a few times only (or even once if "sh -c") */
5722static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00005723{
Denis Vlasenkof9375282009-04-05 19:13:39 +00005724 unsigned sig;
5725 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005726
Denis Vlasenkof9375282009-04-05 19:13:39 +00005727 mask = (1 << SIGQUIT);
5728 if (G_interactive_fd) {
5729 mask = 0
5730 | (1 << SIGQUIT)
5731 | (1 << SIGTERM)
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005732//TODO | (1 << SIGHUP)
Denis Vlasenkof9375282009-04-05 19:13:39 +00005733#if ENABLE_HUSH_JOB
5734 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5735#endif
5736 | (1 << SIGINT)
5737 ;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005738 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005739 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00005740
Denis Vlasenkof9375282009-04-05 19:13:39 +00005741 if (!second_time)
5742 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5743 sig = 0;
5744 while (mask) {
5745 if (mask & 1)
5746 sigaddset(&G.blocked_set, sig);
5747 mask >>= 1;
5748 sig++;
5749 }
5750 sigdelset(&G.blocked_set, SIGCHLD);
5751
5752 sigprocmask(SIG_SETMASK, &G.blocked_set,
5753 second_time ? NULL : &G.inherited_set);
5754 /* POSIX allows shell to re-enable SIGCHLD
5755 * even if it was SIG_IGN on entry */
5756// G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5757 if (!second_time)
5758 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5759}
5760
5761#if ENABLE_HUSH_JOB
5762/* helper */
5763static void maybe_set_to_sigexit(int sig)
5764{
5765 void (*handler)(int);
5766 /* non_DFL_mask'ed signals are, well, masked,
5767 * no need to set handler for them.
5768 */
5769 if (!((G.non_DFL_mask >> sig) & 1)) {
5770 handler = signal(sig, sigexit);
5771 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5772 signal(sig, handler);
5773 }
5774}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005775/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005776static void set_fatal_handlers(void)
5777{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00005778 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005779 if (HUSH_DEBUG) {
5780 maybe_set_to_sigexit(SIGILL );
5781 maybe_set_to_sigexit(SIGFPE );
5782 maybe_set_to_sigexit(SIGBUS );
5783 maybe_set_to_sigexit(SIGSEGV);
5784 maybe_set_to_sigexit(SIGTRAP);
5785 } /* else: hush is perfect. what SEGV? */
5786 maybe_set_to_sigexit(SIGABRT);
5787 /* bash 3.2 seems to handle these just like 'fatal' ones */
5788 maybe_set_to_sigexit(SIGPIPE);
5789 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005790//TODO: disable and move down when proper SIGHUP handling is added
Denis Vlasenkof9375282009-04-05 19:13:39 +00005791 maybe_set_to_sigexit(SIGHUP );
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005792 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00005793 * if we aren't interactive... but in this case
5794 * we never want to restore pgrp on exit, and this fn is not called */
5795 /*maybe_set_to_sigexit(SIGTERM);*/
5796 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00005797}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005798#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00005799
Denis Vlasenkod5762932009-03-31 11:22:57 +00005800static int set_mode(const char cstate, const char mode)
5801{
5802 int state = (cstate == '-' ? 1 : 0);
5803 switch (mode) {
5804 case 'n': G.fake_mode = state; break;
5805 case 'x': /*G.debug_mode = state;*/ break;
5806 default: return EXIT_FAILURE;
5807 }
5808 return EXIT_SUCCESS;
5809}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005810
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00005811int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00005812int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00005813{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005814 static const struct variable const_shell_ver = {
5815 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005816 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005817 .max_len = 1, /* 0 can provoke free(name) */
5818 .flg_export = 1,
5819 .flg_read_only = 1,
5820 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00005821 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005822 int opt;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005823 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005824 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00005825
Denis Vlasenko574f2f42008-02-27 18:41:59 +00005826 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005827 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005828 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005829#if !BB_MMU
5830 G.argv0_for_re_execing = argv[0];
5831#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005832 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005833 G.shell_ver = const_shell_ver; /* copying struct here */
5834 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005835 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005836 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5837 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005838 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005839 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005840 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005841 if (e) while (*e) {
5842 char *value = strchr(*e, '=');
5843 if (value) { /* paranoia */
5844 cur_var->next = xzalloc(sizeof(*cur_var));
5845 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00005846 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005847 cur_var->max_len = strlen(*e);
5848 cur_var->flg_export = 1;
5849 }
5850 e++;
5851 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005852 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005853 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenko38f63192007-01-22 09:03:07 +00005854#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00005855 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00005856#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00005857 G.global_argc = argc;
5858 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00005859 /* Initialize some more globals to non-zero values */
5860 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005861#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00005862 if (ENABLE_FEATURE_EDITING)
5863 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005864 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005865#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00005866
Denis Vlasenkoed782372009-04-10 00:45:02 +00005867 if (setjmp(die_jmp)) {
5868 /* xfunc has failed! die die die */
5869 /* no EXIT traps, this is an escape hatch! */
5870 G.exiting = 1;
5871 hush_exit(xfunc_error_retval);
5872 }
5873
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005874 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005875 * block_signals(0) if we are going to execute "sh <script>",
5876 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005877 * If we later decide that we are interactive, we run block_signals(0)
5878 * (or re-run block_signals(1) if we ran block_signals(0) before)
5879 * in order to intercept (more) signals.
5880 */
5881
5882 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005883 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005884 while (1) {
5885 opt = getopt(argc, argv, "c:xins"
5886#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00005887 "<:$:R:V:"
5888# if ENABLE_HUSH_FUNCTIONS
5889 "F:"
5890# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005891#endif
5892 );
5893 if (opt <= 0)
5894 break;
Eric Andersen25f27032001-04-26 23:22:31 +00005895 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005896 case 'c':
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005897 if (!G.root_pid)
5898 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005899 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00005900 if (!argv[optind]) {
5901 /* -c 'script' (no params): prevent empty $0 */
5902 *--G.global_argv = argv[0];
5903 optind--;
5904 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005905 G.global_argc = argc - optind;
Denis Vlasenkof9375282009-04-05 19:13:39 +00005906 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005907 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005908 goto final_return;
5909 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00005910 /* Well, we cannot just declare interactiveness,
5911 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005912 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005913 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005914 case 's':
5915 /* "-s" means "read from stdin", but this is how we always
5916 * operate, so simply do nothing here. */
5917 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005918#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00005919 case '<': /* "big heredoc" support */
5920 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5921 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005922 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005923 G.root_pid = bb_strtou(optarg, &optarg, 16);
5924 optarg++;
5925 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5926 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005927 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005928# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005929 optarg++;
5930 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005931# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005932 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005933 case 'R':
5934 case 'V':
5935 set_local_var(xstrdup(optarg), 0, opt == 'R');
5936 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00005937# if ENABLE_HUSH_FUNCTIONS
5938 case 'F': {
5939 struct function *funcp = new_function(optarg);
5940 /* funcp->name is already set to optarg */
5941 /* funcp->body is set to NULL. It's a special case. */
5942 funcp->body_as_string = argv[optind];
5943 optind++;
5944 break;
5945 }
5946# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005947#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005948 case 'n':
5949 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00005950 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005951 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005952 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005953#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005954 fprintf(stderr, "Usage: sh [FILE]...\n"
5955 " or: sh -c command [args]...\n\n");
5956 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005957#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005958 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005959#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005960 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005961 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005962
5963 if (!G.root_pid)
5964 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00005965
5966 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005967 if (argv[0] && argv[0][0] == '-') {
5968 FILE *input;
5969 /* XXX what should argv be while sourcing /etc/profile? */
5970 debug_printf("sourcing /etc/profile\n");
5971 input = fopen_for_read("/etc/profile");
5972 if (input != NULL) {
5973 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00005974 block_signals(0); /* 0: called 1st time */
5975 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005976 parse_and_run_file(input);
5977 fclose(input);
5978 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005979 /* bash: after sourcing /etc/profile,
5980 * tries to source (in the given order):
5981 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5982 * stopping of first found. --noprofile turns this off.
5983 * bash also sources ~/.bash_logout on exit.
5984 * If called as sh, skips .bash_XXX files.
5985 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005986 }
5987
Denis Vlasenkof9375282009-04-05 19:13:39 +00005988 if (argv[optind]) {
5989 FILE *input;
5990 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005991 * "bash <script>" (which is never interactive (unless -i?))
5992 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00005993 * If called as sh, does the same but with $ENV.
5994 */
5995 debug_printf("running script '%s'\n", argv[optind]);
5996 G.global_argv = argv + optind;
5997 G.global_argc = argc - optind;
5998 input = xfopen_for_read(argv[optind]);
5999 close_on_exec_on(fileno(input));
6000 if (!signal_mask_is_inited)
6001 block_signals(0); /* 0: called 1st time */
6002 parse_and_run_file(input);
6003#if ENABLE_FEATURE_CLEAN_UP
6004 fclose(input);
6005#endif
6006 goto final_return;
6007 }
6008
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006009 /* Up to here, shell was non-interactive. Now it may become one.
6010 * NB: don't forget to (re)run block_signals(0/1) as needed.
6011 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006012
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006013 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00006014 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006015 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006016 * no arguments remaining or the -s flag given
6017 * standard input is a terminal
6018 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006019 * Refer to Posix.2, the description of the 'sh' utility.
6020 */
6021#if ENABLE_HUSH_JOB
6022 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006023 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
Denis Vlasenkof9375282009-04-05 19:13:39 +00006024 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006025//TODO: "interactive" and "have job control" are two different things.
6026//If tcgetpgrp fails here, "have job control" is false, but "interactive"
6027//should stay on! Currently, we mix these into one.
Denis Vlasenko87a86552008-07-29 19:43:10 +00006028 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006029 /* try to dup stdin to high fd#, >= 255 */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006030 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6031 if (G_interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006032 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006033 G_interactive_fd = dup(STDIN_FILENO);
6034 if (G_interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006035 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006036 G_interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006037 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006038// TODO: track & disallow any attempts of user
6039// to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006040 }
Eric Andersen25f27032001-04-26 23:22:31 +00006041 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006042 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006043 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006044 pid_t shell_pgrp;
6045
6046 /* We are indeed interactive shell, and we will perform
6047 * job control. Setting up for that. */
6048
6049 close_on_exec_on(G_interactive_fd);
6050 /* If we were run as 'hush &', sleep until we are
6051 * in the foreground (tty pgrp == our pgrp).
6052 * If we get started under a job aware app (like bash),
6053 * make sure we are now in charge so we don't fight over
6054 * who gets the foreground */
6055 while (1) {
6056 shell_pgrp = getpgrp();
6057 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6058 if (G.saved_tty_pgrp == shell_pgrp)
6059 break;
6060 /* send TTIN to ourself (should stop us) */
6061 kill(- shell_pgrp, SIGTTIN);
6062 }
6063 /* Block some signals */
6064 block_signals(signal_mask_is_inited);
6065 /* Set other signals to restore saved_tty_pgrp */
6066 set_fatal_handlers();
6067 /* Put ourselves in our own process group */
6068 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6069 /* Grab control of the terminal */
6070 tcsetpgrp(G_interactive_fd, getpid());
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006071 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006072 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006073 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006074 } else if (!signal_mask_is_inited) {
6075 block_signals(0); /* 0: called 1st time */
6076 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006077#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006078 /* No job control compiled in, only prompt/line editing */
6079 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006080 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6081 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006082 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006083 G_interactive_fd = dup(STDIN_FILENO);
6084 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006085 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006086 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006087 }
6088 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006089 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006090 close_on_exec_on(G_interactive_fd);
6091 block_signals(signal_mask_is_inited);
6092 } else if (!signal_mask_is_inited) {
6093 block_signals(0);
6094 }
6095#else
6096 /* We have interactiveness code disabled */
6097 if (!signal_mask_is_inited) {
6098 block_signals(0);
6099 }
6100#endif
6101 /* bash:
6102 * if interactive but not a login shell, sources ~/.bashrc
6103 * (--norc turns this off, --rcfile <file> overrides)
6104 */
6105
6106 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006107 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysingerb2705e12009-03-23 08:44:02 +00006108 printf("Enter 'help' for a list of built-in commands.\n\n");
6109 }
6110
Denis Vlasenkof9375282009-04-05 19:13:39 +00006111 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006112
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006113 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006114#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006115 if (G.cwd != bb_msg_unknown)
6116 free((char*)G.cwd);
6117 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006118 while (cur_var) {
6119 struct variable *tmp = cur_var;
6120 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006121 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006122 cur_var = cur_var->next;
6123 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006124 }
Eric Andersen25f27032001-04-26 23:22:31 +00006125#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006126 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006127}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006128
6129
6130#if ENABLE_LASH
6131int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6132int lash_main(int argc, char **argv)
6133{
6134 //bb_error_msg("lash is deprecated, please use hush instead");
6135 return hush_main(argc, argv);
6136}
6137#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006138
6139
6140/*
6141 * Built-ins
6142 */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006143static int builtin_trap(char **argv)
6144{
Denis Vlasenkod5762932009-03-31 11:22:57 +00006145 int i;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006146 int sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006147 char *new_cmd;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006148
6149 if (!G.traps)
Denis Vlasenkod5762932009-03-31 11:22:57 +00006150 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006151
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006152 argv++;
6153 if (!*argv) {
6154 /* No args: print all trapped. This isn't 100% correct as we
6155 * should be escaping the cmd so that it can be pasted back in
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006156 */
6157 for (i = 0; i < NSIG; ++i)
Denis Vlasenkod5762932009-03-31 11:22:57 +00006158 if (G.traps[i])
6159 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006160 return EXIT_SUCCESS;
6161 }
6162
Denis Vlasenkod5762932009-03-31 11:22:57 +00006163 new_cmd = NULL;
6164 i = 0;
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006165 /* If first arg is decimal: reset all specified signals */
6166 sig = bb_strtou(*argv, NULL, 10);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006167 if (errno == 0) {
6168 int ret;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006169 set_all:
6170 ret = EXIT_SUCCESS;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006171 while (*argv) {
6172 sig = get_signum(*argv++);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006173 if (sig < 0 || sig >= NSIG) {
6174 ret = EXIT_FAILURE;
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006175 /* Mimic bash message exactly */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006176 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
6177 continue;
6178 }
6179
Denis Vlasenkod5762932009-03-31 11:22:57 +00006180 free(G.traps[sig]);
6181 G.traps[sig] = xstrdup(new_cmd);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006182
Denis Vlasenkod5762932009-03-31 11:22:57 +00006183 debug_printf("trap: setting SIG%s (%i) to '%s'",
6184 get_signame(sig), sig, G.traps[sig]);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006185
6186 /* There is no signal for 0 (EXIT) */
6187 if (sig == 0)
6188 continue;
6189
6190 if (new_cmd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006191 sigaddset(&G.blocked_set, sig);
6192 } else {
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006193 /* There was a trap handler, we are removing it
Denis Vlasenkod5762932009-03-31 11:22:57 +00006194 * (if sig has non-DFL handling,
6195 * we don't need to do anything) */
6196 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6197 continue;
6198 sigdelset(&G.blocked_set, sig);
6199 }
6200 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006201 }
6202 return ret;
6203 }
6204
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006205 /* First arg is "-": reset all specified to default */
6206 /* First arg is "": ignore all specified */
6207 /* Everything else: execute first arg upon signal */
Denis Vlasenkod5762932009-03-31 11:22:57 +00006208 if (!argv[1]) {
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006209 bb_error_msg("trap: invalid arguments");
6210 return EXIT_FAILURE;
6211 }
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00006212 if (NOT_LONE_DASH(*argv))
Denis Vlasenkod5762932009-03-31 11:22:57 +00006213 new_cmd = *argv;
6214 argv++;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00006215 goto set_all;
6216}
6217
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006218static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006219{
6220 return 0;
6221}
6222
6223static int builtin_test(char **argv)
6224{
6225 int argc = 0;
6226 while (*argv) {
6227 argc++;
6228 argv++;
6229 }
6230 return test_main(argc, argv - argc);
6231}
6232
6233static int builtin_echo(char **argv)
6234{
6235 int argc = 0;
6236 while (*argv) {
6237 argc++;
6238 argv++;
6239 }
6240 return echo_main(argc, argv - argc);
6241}
6242
6243static int builtin_eval(char **argv)
6244{
6245 int rcode = EXIT_SUCCESS;
6246
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006247 if (*++argv) {
6248 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006249 /* bash:
6250 * eval "echo Hi; done" ("done" is syntax error):
6251 * "echo Hi" will not execute too.
6252 */
6253 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006254 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006255 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006256 }
6257 return rcode;
6258}
6259
6260static int builtin_cd(char **argv)
6261{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006262 const char *newdir = argv[1];
6263 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006264 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006265 * bash says "bash: cd: HOME not set" and does nothing
6266 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006267 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006268 newdir = getenv("HOME") ? : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006269 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006270 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006271 /* Mimic bash message exactly */
6272 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006273 return EXIT_FAILURE;
6274 }
6275 set_cwd();
6276 return EXIT_SUCCESS;
6277}
6278
6279static int builtin_exec(char **argv)
6280{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006281 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006282 return EXIT_SUCCESS; /* bash does this */
6283 {
6284#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006285 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006286#endif
6287// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006288 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006289 /* never returns */
6290 }
6291}
6292
6293static int builtin_exit(char **argv)
6294{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006295 debug_printf_exec("%s()\n", __func__);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006296// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
6297 //puts("exit"); /* bash does it */
6298// TODO: warn if we have background jobs: "There are stopped jobs"
6299// On second consecutive 'exit', exit anyway.
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006300// perhaps use G.exiting = -1 as indicator "last cmd was exit"
6301
6302 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006303 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006304 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006305 /* mimic bash: exit 123abc == exit 255 + error msg */
6306 xfunc_error_retval = 255;
6307 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006308 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006309}
6310
6311static int builtin_export(char **argv)
6312{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006313 if (*++argv == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006314 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006315 if (e) {
6316 while (*e) {
6317#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006318 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006319#else
6320 /* ash emits: export VAR='VAL'
6321 * bash: declare -x VAR="VAL"
6322 * we follow ash example */
6323 const char *s = *e++;
6324 const char *p = strchr(s, '=');
6325
6326 if (!p) /* wtf? take next variable */
6327 continue;
6328 /* export var= */
6329 printf("export %.*s", (int)(p - s) + 1, s);
6330 s = p + 1;
6331 while (*s) {
6332 if (*s != '\'') {
6333 p = strchrnul(s, '\'');
6334 /* print 'xxxx' */
6335 printf("'%.*s'", (int)(p - s), s);
6336 if (*p == '\0')
6337 break;
6338 s = p;
6339 }
6340 /* s points to '; print ''...'''" */
6341 putchar('"');
6342 do putchar('\''); while (*++s == '\'');
6343 putchar('"');
6344 }
6345 putchar('\n');
6346#endif
6347 }
6348 fflush(stdout);
6349 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006350 return EXIT_SUCCESS;
6351 }
6352
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006353 do {
6354 const char *value;
6355 char *name = *argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006356
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006357 value = strchr(name, '=');
6358 if (!value) {
6359 /* They are exporting something without a =VALUE */
6360 struct variable *var;
6361
6362 var = get_local_var(name);
6363 if (var) {
6364 var->flg_export = 1;
6365 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6366 putenv(var->varstr);
6367 }
6368 /* bash does not return an error when trying to export
6369 * an undefined variable. Do likewise. */
6370 continue;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006371 }
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006372 set_local_var(xstrdup(name), 1, 0);
6373 } while (*++argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006374
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006375 return EXIT_SUCCESS;
6376}
6377
6378#if ENABLE_HUSH_JOB
6379/* built-in 'fg' and 'bg' handler */
6380static int builtin_fg_bg(char **argv)
6381{
6382 int i, jobnum;
6383 struct pipe *pi;
6384
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006385 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006386 return EXIT_FAILURE;
6387 /* If they gave us no args, assume they want the last backgrounded task */
6388 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006389 for (pi = G.job_list; pi; pi = pi->next) {
6390 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006391 goto found;
6392 }
6393 }
6394 bb_error_msg("%s: no current job", argv[0]);
6395 return EXIT_FAILURE;
6396 }
6397 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6398 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6399 return EXIT_FAILURE;
6400 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006401 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006402 if (pi->jobid == jobnum) {
6403 goto found;
6404 }
6405 }
6406 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6407 return EXIT_FAILURE;
6408 found:
6409 // TODO: bash prints a string representation
6410 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006411 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006412 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006413 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006414 }
6415
6416 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006417 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6418 for (i = 0; i < pi->num_cmds; i++) {
6419 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6420 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006421 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006422 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006423
6424 i = kill(- pi->pgrp, SIGCONT);
6425 if (i < 0) {
6426 if (errno == ESRCH) {
6427 delete_finished_bg_job(pi);
6428 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006429 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006430 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006431 }
6432
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006433 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006434 remove_bg_job(pi);
6435 return checkjobs_and_fg_shell(pi);
6436 }
6437 return EXIT_SUCCESS;
6438}
6439#endif
6440
6441#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006442static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006443{
6444 const struct built_in_command *x;
6445
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006446 printf("\n"
6447 "Built-in commands:\n"
6448 "------------------\n");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006449 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6450 printf("%s\t%s\n", x->cmd, x->descr);
6451 }
6452 printf("\n\n");
6453 return EXIT_SUCCESS;
6454}
6455#endif
6456
6457#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006458static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006459{
6460 struct pipe *job;
6461 const char *status_string;
6462
Denis Vlasenko87a86552008-07-29 19:43:10 +00006463 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006464 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006465 status_string = "Stopped";
6466 else
6467 status_string = "Running";
6468
6469 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6470 }
6471 return EXIT_SUCCESS;
6472}
6473#endif
6474
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00006475#if HUSH_DEBUG
6476static int builtin_memleak(char **argv UNUSED_PARAM)
6477{
6478 void *p;
6479 unsigned long l;
6480
6481 /* Crude attempt to find where "free memory" starts,
6482 * sans fragmentation. */
6483 p = malloc(240);
6484 l = (unsigned long)p;
6485 free(p);
6486 p = malloc(3400);
6487 if (l < (unsigned long)p) l = (unsigned long)p;
6488 free(p);
6489
6490 if (!G.memleak_value)
6491 G.memleak_value = l;
6492
6493 l -= G.memleak_value;
6494 if ((long)l < 0)
6495 l = 0;
6496 l /= 1024;
6497 if (l > 127)
6498 l = 127;
6499
6500 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6501 return l;
6502}
6503#endif
6504
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006505static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006506{
6507 puts(set_cwd());
6508 return EXIT_SUCCESS;
6509}
6510
6511static int builtin_read(char **argv)
6512{
6513 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006514 const char *name = "REPLY";
6515
6516 if (argv[1]) {
6517 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006518 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6519 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006520 if (!is_well_formed_var_name(name, '\0')) {
6521 /* Mimic bash message */
6522 bb_error_msg("read: '%s': not a valid identifier", name);
6523 return 1;
6524 }
6525 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006526
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006527//TODO: bash unbackslashes input, splits words and puts them in argv[i]
6528
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006529 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006530 return set_local_var(string, 0, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006531}
6532
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006533/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6534 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006535 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006536 * set [-abCefhmnuvx] [-o option] [argument...]
6537 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006538 * set -- [argument...]
6539 * set -o
6540 * set +o
6541 * Implementations shall support the options in both their hyphen and
6542 * plus-sign forms. These options can also be specified as options to sh.
6543 * Examples:
6544 * Write out all variables and their values: set
6545 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6546 * Turn on the -x and -v options: set -xv
6547 * Unset all positional parameters: set --
6548 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6549 * Set the positional parameters to the expansion of x, even if x expands
6550 * with a leading '-' or '+': set -- $x
6551 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006552 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006553 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006554static int builtin_set(char **argv)
6555{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006556 int n;
6557 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006558 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006559
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006560 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006561 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00006562 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006563 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006564 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006565 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006566
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006567 do {
6568 if (!strcmp(arg, "--")) {
6569 ++argv;
6570 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006571 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00006572 if (arg[0] != '+' && arg[0] != '-')
6573 break;
6574 for (n = 1; arg[n]; ++n)
6575 if (set_mode(arg[0], arg[n]))
6576 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006577 } while ((arg = *++argv) != NULL);
6578 /* Now argv[0] is 1st argument */
6579
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006580 if (arg == NULL)
6581 return EXIT_SUCCESS;
6582 set_argv:
6583
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006584 /* NB: G.global_argv[0] ($0) is never freed/changed */
6585 g_argv = G.global_argv;
6586 if (G.global_args_malloced) {
6587 pp = g_argv;
6588 while (*++pp)
6589 free(*pp);
6590 g_argv[1] = NULL;
6591 } else {
6592 G.global_args_malloced = 1;
6593 pp = xzalloc(sizeof(pp[0]) * 2);
6594 pp[0] = g_argv[0]; /* retain $0 */
6595 g_argv = pp;
6596 }
6597 /* This realloc's G.global_argv */
6598 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6599
6600 n = 1;
6601 while (*++pp)
6602 n++;
6603 G.global_argc = n;
6604
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006605 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006606
6607 /* Nothing known, so abort */
6608 error:
6609 bb_error_msg("set: %s: invalid option", arg);
6610 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006611}
6612
6613static int builtin_shift(char **argv)
6614{
6615 int n = 1;
6616 if (argv[1]) {
6617 n = atoi(argv[1]);
6618 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006619 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006620 if (G.global_args_malloced) {
6621 int m = 1;
6622 while (m <= n)
6623 free(G.global_argv[m++]);
6624 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006625 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006626 memmove(&G.global_argv[1], &G.global_argv[n+1],
6627 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006628 return EXIT_SUCCESS;
6629 }
6630 return EXIT_FAILURE;
6631}
6632
6633static int builtin_source(char **argv)
6634{
6635 FILE *input;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006636
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006637 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006638 return EXIT_FAILURE;
6639
6640 /* XXX search through $PATH is missing */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006641 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006642 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006643 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006644 return EXIT_FAILURE;
6645 }
6646 close_on_exec_on(fileno(input));
6647
6648 /* Now run the file */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006649//TODO:
Denis Vlasenko87a86552008-07-29 19:43:10 +00006650 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006651 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00006652 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006653 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006654 fclose(input);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006655 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006656}
6657
6658static int builtin_umask(char **argv)
6659{
6660 mode_t new_umask;
6661 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006662 if (arg) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006663//TODO: umask may take chmod-like symbolic masks
Mike Frysinger40b8dc42009-03-29 00:50:30 +00006664 new_umask = bb_strtou(arg, NULL, 8);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006665 if (errno) {
6666 //Message? bash examples:
6667 //bash: umask: 'q': invalid symbolic mode operator
6668 //bash: umask: 999: octal number out of range
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006669 return EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006670 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006671 } else {
6672 new_umask = umask(0);
6673 printf("%.3o\n", (unsigned) new_umask);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006674 /* fall through and restore new_umask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006675 }
6676 umask(new_umask);
6677 return EXIT_SUCCESS;
6678}
6679
Mike Frysingerd690f682009-03-30 06:50:54 +00006680/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006681static int builtin_unset(char **argv)
6682{
Mike Frysingerd690f682009-03-30 06:50:54 +00006683 int ret;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006684 char var;
Mike Frysingerd690f682009-03-30 06:50:54 +00006685
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006686 if (!*++argv)
Mike Frysingerd690f682009-03-30 06:50:54 +00006687 return EXIT_SUCCESS;
6688
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006689 var = 'v';
6690 if (argv[0][0] == '-') {
6691 switch (argv[0][1]) {
6692 case 'v':
6693 case 'f':
6694 var = argv[0][1];
6695 break;
Mike Frysingerd690f682009-03-30 06:50:54 +00006696 default:
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006697 bb_error_msg("unset: %s: invalid option", *argv);
Mike Frysingerd690f682009-03-30 06:50:54 +00006698 return EXIT_FAILURE;
6699 }
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006700//TODO: disallow "unset -vf ..." too
6701 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006702 }
6703
6704 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006705 while (*argv) {
6706 if (var == 'v') {
6707 if (unset_local_var(*argv)) {
6708 /* unset <nonexistent_var> doesn't fail.
6709 * Error is when one tries to unset RO var.
6710 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00006711 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006712 }
Mike Frysingerd690f682009-03-30 06:50:54 +00006713 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00006714//#if ENABLE_HUSH_FUNCTIONS
6715// else {
6716// unset_local_func(*argv);
6717// }
6718//#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006719 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006720 }
6721 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006722}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006723
Mike Frysinger56bdea12009-03-28 20:01:58 +00006724/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6725static int builtin_wait(char **argv)
6726{
6727 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006728 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006729
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006730 if (*++argv == NULL) {
6731 /* Don't care about wait results */
6732 /* Note 1: must wait until there are no more children */
6733 /* Note 2: must be interruptible */
6734 /* Examples:
6735 * $ sleep 3 & sleep 6 & wait
6736 * [1] 30934 sleep 3
6737 * [2] 30935 sleep 6
6738 * [1] Done sleep 3
6739 * [2] Done sleep 6
6740 * $ sleep 3 & sleep 6 & wait
6741 * [1] 30936 sleep 3
6742 * [2] 30937 sleep 6
6743 * [1] Done sleep 3
6744 * ^C <-- after ~4 sec from keyboard
6745 * $
6746 */
6747 sigaddset(&G.blocked_set, SIGCHLD);
6748 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6749 while (1) {
6750 checkjobs(NULL);
6751 if (errno == ECHILD)
6752 break;
6753 /* Wait for SIGCHLD or any other signal of interest */
6754 /* sigtimedwait with infinite timeout: */
6755 sig = sigwaitinfo(&G.blocked_set, NULL);
6756 if (sig > 0) {
6757 sig = check_and_run_traps(sig);
6758 if (sig && sig != SIGCHLD) { /* see note 2 */
6759 ret = 128 + sig;
6760 break;
6761 }
6762 }
6763 }
6764 sigdelset(&G.blocked_set, SIGCHLD);
6765 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6766 return ret;
6767 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00006768
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006769 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00006770 while (*argv) {
6771 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00006772 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006773 /* mimic bash message */
6774 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00006775 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006776 }
6777 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00006778 if (WIFSIGNALED(status))
6779 ret = 128 + WTERMSIG(status);
6780 else if (WIFEXITED(status))
6781 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00006782 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00006783 ret = EXIT_FAILURE;
6784 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006785 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00006786 ret = 127;
6787 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00006788 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006789 }
6790
6791 return ret;
6792}
6793
Denis Vlasenkodadfb492008-07-29 10:16:05 +00006794#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006795static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006796{
Denis Vlasenko87a86552008-07-29 19:43:10 +00006797 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006798 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00006799 return EXIT_SUCCESS; /* bash compat */
6800 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006801 G.flag_break_continue++; /* BC_BREAK = 1 */
6802 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006803 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006804 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6805 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006806 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00006807 G.flag_break_continue = BC_BREAK;
6808 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006809 }
6810 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006811 if (G.depth_of_loop < G.depth_break_continue)
6812 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006813 return EXIT_SUCCESS;
6814}
6815
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006816static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006817{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006818 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6819 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006820}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00006821#endif