blob: 45a9733cf24bab3b76aaca1036cdfb9d86902499 [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 Vlasenko6b9e0532009-04-18 01:23:21 +000055 * builtins: 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 * separate job control from interactiveness
60 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
Eric Andersen25f27032001-04-26 23:22:31 +000061 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000062 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000063 */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000064#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000065#include <glob.h>
66/* #include <dmalloc.h> */
67#if ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000068# include <fnmatch.h>
Denis Vlasenkobe709c22008-07-28 00:01:16 +000069#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000070#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000071#include "match.h"
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000072#ifndef PIPE_BUF
73# define PIPE_BUF 4096 /* amount of buffering in a pipe */
74#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000075
Denis Vlasenko1943aec2009-04-09 14:15:57 +000076
77/* Debug build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000078#define LEAK_HUNTING 0
79#define BUILD_AS_NOMMU 0
80/* Enable/disable sanity checks. Ok to enable in production,
81 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
82 * Keeping 1 for now even in released versions.
83 */
84#define HUSH_DEBUG 1
Denis Vlasenko1943aec2009-04-09 14:15:57 +000085
86
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000087#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +000088# undef BB_MMU
89# undef USE_FOR_NOMMU
90# undef USE_FOR_MMU
91# define BB_MMU 0
92# define USE_FOR_NOMMU(...) __VA_ARGS__
93# define USE_FOR_MMU(...)
94#endif
95
Denis Vlasenko61befda2008-11-25 01:36:03 +000096#if defined SINGLE_APPLET_MAIN
97/* STANDALONE does not make sense, and won't compile */
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +000098# undef CONFIG_FEATURE_SH_STANDALONE
99# undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000100# undef IF_FEATURE_SH_STANDALONE
101# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000102# define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000103# define IF_FEATURE_SH_STANDALONE(...)
104# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Denis Vlasenko61befda2008-11-25 01:36:03 +0000105#endif
106
Denis Vlasenko05743d72008-02-10 12:10:08 +0000107#if !ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000108# undef ENABLE_FEATURE_EDITING
109# define ENABLE_FEATURE_EDITING 0
110# undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
111# define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000112#endif
113
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000114/* Do we support ANY keywords? */
115#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000116# define HAS_KEYWORDS 1
117# define IF_HAS_KEYWORDS(...) __VA_ARGS__
118# define IF_HAS_NO_KEYWORDS(...)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000119#else
Denis Vlasenkoce4acbb2009-04-10 23:23:41 +0000120# define HAS_KEYWORDS 0
121# define IF_HAS_KEYWORDS(...)
122# define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000123#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000124
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000125/* If you comment out one of these below, it will be #defined later
126 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000127#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000128/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000129#define debug_printf_parse(...) do {} while (0)
130#define debug_print_tree(a, b) do {} while (0)
131#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000132#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000133#define debug_printf_jobs(...) do {} while (0)
134#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000135#define debug_printf_glob(...) do {} while (0)
136#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000137#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000138#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000139
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000140#define ERR_PTR ((void*)(long)1)
141
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000142#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000143
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000144#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000145
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000146static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
147
148/* This supports saving pointers malloced in vfork child,
Denis Vlasenkoc376db32009-04-15 21:49:48 +0000149 * to be freed in the parent.
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000150 */
151#if !BB_MMU
152typedef struct nommu_save_t {
153 char **new_env;
154 char **old_env;
155 char **argv;
Denis Vlasenko27014ed2009-04-15 21:48:23 +0000156 char **argv_from_re_execing;
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000157} nommu_save_t;
158#endif
159
Denis Vlasenko55789c62008-06-18 16:30:42 +0000160/* The descrip member of this structure is only used to make
161 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000162static const struct {
163 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000164 signed char default_fd;
165 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000166} redir_table[] = {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000167 { 0, 0, "??" },
Eric Andersen25f27032001-04-26 23:22:31 +0000168 { O_RDONLY, 0, "<" },
169 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
170 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000171 { O_RDONLY, 0, "<<" },
172 { O_CREAT|O_RDWR, 1, "<>" },
173/* Should not be needed. Bogus default_fd helps in debugging */
174/* { O_RDONLY, 77, "<<" }, */
Eric Andersen25f27032001-04-26 23:22:31 +0000175};
176
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000177typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000178 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000179#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000180 RES_IF ,
181 RES_THEN ,
182 RES_ELIF ,
183 RES_ELSE ,
184 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000185#endif
186#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000187 RES_FOR ,
188 RES_WHILE ,
189 RES_UNTIL ,
190 RES_DO ,
191 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000192#endif
193#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000194 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000195#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000196#if ENABLE_HUSH_CASE
197 RES_CASE ,
198 /* two pseudo-keywords support contrived "case" syntax: */
199 RES_MATCH , /* "word)" */
200 RES_CASEI , /* "this command is inside CASE" */
201 RES_ESAC ,
202#endif
203 RES_XXXX ,
204 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000205} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000206
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000207typedef struct o_string {
208 char *data;
209 int length; /* position where data is appended */
210 int maxlen;
211 /* Protect newly added chars against globbing
212 * (by prepending \ to *, ?, [, \) */
213 smallint o_escape;
214 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000215 /* At least some part of the string was inside '' or "",
216 * possibly empty one: word"", wo''rd etc. */
217 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000218 smallint has_empty_slot;
219 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
220} o_string;
221enum {
222 MAYBE_ASSIGNMENT = 0,
223 DEFINITELY_ASSIGNMENT = 1,
224 NOT_ASSIGNMENT = 2,
225 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
226};
227/* Used for initialization: o_string foo = NULL_O_STRING; */
228#define NULL_O_STRING { NULL }
229
230/* I can almost use ordinary FILE*. Is open_memstream() universally
231 * available? Where is it documented? */
232typedef struct in_str {
233 const char *p;
234 /* eof_flag=1: last char in ->p is really an EOF */
235 char eof_flag; /* meaningless if ->p == NULL */
236 char peek_buf[2];
237#if ENABLE_HUSH_INTERACTIVE
238 smallint promptme;
239 smallint promptmode; /* 0: PS1, 1: PS2 */
240#endif
241 FILE *file;
242 int (*get) (struct in_str *);
243 int (*peek) (struct in_str *);
244} in_str;
245#define i_getch(input) ((input)->get(input))
246#define i_peek(input) ((input)->peek(input))
247
Eric Andersen25f27032001-04-26 23:22:31 +0000248struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000249 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000250 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000251 int rd_fd; /* fd to redirect */
252 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
253 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000254 smallint rd_type; /* (enum redir_type) */
255 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000256 * and subsequently heredoc itself; and rd_dup is a bitmask:
257 * 1: do we need to trim leading tabs?
Denis Vlasenkoed055212009-04-11 10:37:10 +0000258 * 2: is heredoc quoted (<<'delim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000259 */
Eric Andersen25f27032001-04-26 23:22:31 +0000260};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000261typedef enum redir_type {
262 REDIRECT_INVALID = 0,
263 REDIRECT_INPUT = 1,
264 REDIRECT_OVERWRITE = 2,
265 REDIRECT_APPEND = 3,
266 REDIRECT_HEREDOC = 4,
267 REDIRECT_IO = 5,
268 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000269
270 REDIRFD_CLOSE = -3,
271 REDIRFD_SYNTAX_ERR = -2,
Denis Vlasenko835fcfd2009-04-10 13:51:56 +0000272 REDIRFD_TO_FILE = -1,
273 /* otherwise, rd_fd is redirected to rd_dup */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000274
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000275 HEREDOC_SKIPTABS = 1,
276 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000277} redir_type;
278
Eric Andersen25f27032001-04-26 23:22:31 +0000279
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000280struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000281 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000282 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000283 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000284 smallint grp_type; /* GRP_xxx */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000285#define GRP_NORMAL 0
286#define GRP_SUBSHELL 1
287#if ENABLE_HUSH_FUNCTIONS
288# define GRP_FUNCTION 2
289#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000290 struct pipe *group; /* if non-NULL, this "command" is { list },
291 * ( list ), or a compound statement */
292#if !BB_MMU
293 char *group_as_string;
294#endif
Denis Vlasenkoed055212009-04-11 10:37:10 +0000295#if ENABLE_HUSH_FUNCTIONS
296 struct function *child_func;
297/* This field is used to prevent a bug here:
298 * while...do f1() {a;}; f1; f1 {b;}; f1; done
299 * When we execute "f1() {a;}" cmd, we create new function and clear
300 * cmd->group, cmd->group_as_string, cmd->argv[0].
301 * when we execute "f1 {b;}", we notice that f1 exists,
302 * and that it's "parent cmd" struct is still "alive",
303 * we put those fields back into cmd->xxx
304 * (struct function has ->parent_cmd ptr to facilitate that).
305 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
306 * Without this trick, loop would execute a;b;b;b;...
307 * instead of correct sequence a;b;a;b;...
308 * When command is freed, it severs the link
309 * (sets ->child_func->parent_cmd to NULL).
310 */
311#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000312 char **argv; /* command name and arguments */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000313/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
314 * and on execution these are substituted with their values.
315 * Substitution can make _several_ words out of one argv[n]!
316 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000317 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000318 */
Denis Vlasenkoed055212009-04-11 10:37:10 +0000319 struct redir_struct *redirects; /* I/O redirections */
320};
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000321/* Is there anything in this command at all? */
322#define IS_NULL_CMD(cmd) \
323 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
324
Eric Andersen25f27032001-04-26 23:22:31 +0000325
326struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000327 struct pipe *next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000328 int num_cmds; /* total number of commands in pipe */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000329 int alive_cmds; /* number of commands running (not exited) */
330 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000331#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000332 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000333 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000334 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000335#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000336 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000337 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000338 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
339 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000340};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000341typedef enum pipe_style {
342 PIPE_SEQ = 1,
343 PIPE_AND = 2,
344 PIPE_OR = 3,
345 PIPE_BG = 4,
346} pipe_style;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +0000347/* Is there anything in this pipe at all? */
348#define IS_NULL_PIPE(pi) \
349 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
Eric Andersen25f27032001-04-26 23:22:31 +0000350
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000351/* This holds pointers to the various results of parsing */
352struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000353 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000354 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000355 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000356 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000357 /* last command in pipe (being constructed right now) */
358 struct command *command;
359 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000360 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000361#if !BB_MMU
362 o_string as_string;
363#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000364#if HAS_KEYWORDS
365 smallint ctx_res_w;
366 smallint ctx_inverted; /* "! cmd | cmd" */
367#if ENABLE_HUSH_CASE
368 smallint ctx_dsemicolon; /* ";;" seen */
369#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000370 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
371 int old_flag;
372 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000373 * example: "if pipe1; pipe2; then pipe3; fi"
374 * when we see "if" or "then", we malloc and copy current context,
375 * and make ->stack point to it. then we parse pipeN.
376 * when closing "then" / fi" / whatever is found,
377 * we move list_head into ->stack->command->group,
378 * copy ->stack into current context, and delete ->stack.
379 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000380 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000381 struct parse_context *stack;
382#endif
383};
384
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000385/* On program start, environ points to initial environment.
386 * putenv adds new pointers into it, unsetenv removes them.
387 * Neither of these (de)allocates the strings.
388 * setenv allocates new strings in malloc space and does putenv,
389 * and thus setenv is unusable (leaky) for shell's purposes */
390#define setenv(...) setenv_is_leaky_dont_use()
391struct variable {
392 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000393 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000394 int max_len; /* if > 0, name is part of initial env; else name is malloced */
395 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000396 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000397};
398
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000399enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000400 BC_BREAK = 1,
401 BC_CONTINUE = 2,
402};
403
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000404#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000405struct function {
406 struct function *next;
407 char *name;
Denis Vlasenkoed055212009-04-11 10:37:10 +0000408 struct command *parent_cmd;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000409 struct pipe *body;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000410#if !BB_MMU
411 char *body_as_string;
412#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000413};
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000414#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000415
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000416
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000417/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000418/* Sorted roughly by size (smaller offsets == smaller code) */
419struct globals {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000420 /* interactive_fd != 0 means we are an interactive shell.
421 * If we are, then saved_tty_pgrp can also be != 0, meaning
422 * that controlling tty is available. With saved_tty_pgrp == 0,
423 * job control still works, but terminal signals
424 * (^C, ^Z, ^Y, ^\) won't work at all, and background
425 * process groups can only be created with "cmd &".
426 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
427 * to give tty to the foreground process group,
428 * and will take it back when the group is stopped (^Z)
429 * or killed (^C).
430 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000431#if ENABLE_HUSH_INTERACTIVE
432 /* 'interactive_fd' is a fd# open to ctty, if we have one
433 * _AND_ if we decided to act interactively */
434 int interactive_fd;
435 const char *PS1;
436 const char *PS2;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000437# define G_interactive_fd (G.interactive_fd)
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000438#else
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000439# define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000440#endif
441#if ENABLE_FEATURE_EDITING
442 line_input_t *line_input_state;
443#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000444 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000445 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000446#if ENABLE_HUSH_JOB
447 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000448 int last_jobid;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000449 pid_t saved_tty_pgrp;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000450 struct pipe *job_list;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000451#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000452 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000453#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000454 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000455#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000456#if ENABLE_HUSH_FUNCTIONS
457 /* 0: outside of a function (or sourced file)
458 * -1: inside of a function, ok to use return builtin
Denis Vlasenkoc8653f62009-04-27 23:29:14 +0000459 * 1: return is invoked, skip all till end of func
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000460 */
461 smallint flag_return_in_progress;
462#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000463 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000464 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000465 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000466 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000467 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000468 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000469 /* how many non-NULL argv's we have. NB: $# + 1 */
470 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000471 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000472#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000473 char *argv0_for_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000474#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000475#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000476 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000477 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000478#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000479 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000480 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000481 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000482 struct variable shell_ver;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000483#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +0000484 struct function *top_func;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000485#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +0000486 /* Signal and trap handling */
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000487// unsigned count_SIGCHLD;
488// unsigned handled_SIGCHLD;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000489 /* which signals have non-DFL handler (even with no traps set)? */
490 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000491 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000492 sigset_t blocked_set;
493 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000494#if HUSH_DEBUG
495 unsigned long memleak_value;
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000496 int debug_indent;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000497#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000498 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000499};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000500#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000501/* Not #defining name to G.name - this quickly gets unwieldy
502 * (too many defines). Also, I actually prefer to see when a variable
503 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000504#define INIT_G() do { \
505 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
506} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000507
508
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000509/* Function prototypes for builtins */
510static int builtin_cd(char **argv);
511static int builtin_echo(char **argv);
512static int builtin_eval(char **argv);
513static int builtin_exec(char **argv);
514static int builtin_exit(char **argv);
515static int builtin_export(char **argv);
516#if ENABLE_HUSH_JOB
517static int builtin_fg_bg(char **argv);
518static int builtin_jobs(char **argv);
519#endif
520#if ENABLE_HUSH_HELP
521static int builtin_help(char **argv);
522#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000523#if HUSH_DEBUG
524static int builtin_memleak(char **argv);
525#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000526static int builtin_pwd(char **argv);
527static int builtin_read(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000528static int builtin_set(char **argv);
529static int builtin_shift(char **argv);
530static int builtin_source(char **argv);
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000531static int builtin_test(char **argv);
532static int builtin_trap(char **argv);
533static int builtin_true(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000534static int builtin_umask(char **argv);
535static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000536static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000537#if ENABLE_HUSH_LOOPS
538static int builtin_break(char **argv);
539static int builtin_continue(char **argv);
540#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000541#if ENABLE_HUSH_FUNCTIONS
542static int builtin_return(char **argv);
543#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000544
545/* Table of built-in functions. They can be forked or not, depending on
546 * context: within pipes, they fork. As simple commands, they do not.
547 * When used in non-forking context, they can change global variables
548 * in the parent shell process. If forked, of course they cannot.
549 * For example, 'unset foo | whatever' will parse and run, but foo will
550 * still be set at the end. */
551struct built_in_command {
552 const char *cmd;
553 int (*function)(char **argv);
554#if ENABLE_HUSH_HELP
555 const char *descr;
556#define BLTIN(cmd, func, help) { cmd, func, help }
557#else
558#define BLTIN(cmd, func, help) { cmd, func }
559#endif
560};
561
562/* For now, echo and test are unconditionally enabled.
563 * Maybe make it configurable? */
564static const struct built_in_command bltins[] = {
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000565 BLTIN("." , builtin_source , "Run commands in a file"),
566 BLTIN(":" , builtin_true , "No-op"),
567 BLTIN("[" , builtin_test , "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000568#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000569 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000570#endif
571#if ENABLE_HUSH_LOOPS
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000572 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000573#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000574 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000575#if ENABLE_HUSH_LOOPS
576 BLTIN("continue", builtin_continue, "Start new loop iteration"),
577#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000578 BLTIN("echo" , builtin_echo , "Write to stdout"),
579 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
580 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
581 BLTIN("exit" , builtin_exit , "Exit"),
582 BLTIN("export" , builtin_export , "Set environment variable"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000583#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000584 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000585#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000586#if ENABLE_HUSH_HELP
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000587 BLTIN("help" , builtin_help , "List shell built-in commands"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000588#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000589#if ENABLE_HUSH_JOB
590 BLTIN("jobs" , builtin_jobs , "List active jobs"),
591#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000592#if HUSH_DEBUG
593 BLTIN("memleak" , builtin_memleak , "Debug tool"),
594#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000595 BLTIN("pwd" , builtin_pwd , "Print current directory"),
596 BLTIN("read" , builtin_read , "Input environment variable"),
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +0000597#if ENABLE_HUSH_FUNCTIONS
598 BLTIN("return" , builtin_return , "Return from a function"),
599#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000600 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
601 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
602 BLTIN("test" , builtin_test , "Test condition"),
603 BLTIN("trap" , builtin_trap , "Trap signals"),
604// BLTIN("ulimit" , builtin_return , "Control resource limits"),
605 BLTIN("umask" , builtin_umask , "Set file creation mask"),
606 BLTIN("unset" , builtin_unset , "Unset environment variable"),
607 BLTIN("wait" , builtin_wait , "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000608};
609
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000610
Denis Vlasenko0701dca2009-04-11 10:38:47 +0000611/* Debug printouts.
612 */
613#if HUSH_DEBUG
614/* prevent disasters with G.debug_indent < 0 */
615# define indent() fprintf(stderr, "%*s", (G.debug_indent * 2) & 0xff, "")
616# define debug_enter() (G.debug_indent++)
617# define debug_leave() (G.debug_indent--)
618#else
619# define indent() ((void)0)
620# define debug_enter() ((void)0)
621# define debug_leave() ((void)0)
622#endif
623
624#ifndef debug_printf
625# define debug_printf(...) (indent(), fprintf(stderr, __VA_ARGS__))
626#endif
627
628#ifndef debug_printf_parse
629# define debug_printf_parse(...) (indent(), fprintf(stderr, __VA_ARGS__))
630#endif
631
632#ifndef debug_printf_exec
633#define debug_printf_exec(...) (indent(), fprintf(stderr, __VA_ARGS__))
634#endif
635
636#ifndef debug_printf_env
637# define debug_printf_env(...) (indent(), fprintf(stderr, __VA_ARGS__))
638#endif
639
640#ifndef debug_printf_jobs
641# define debug_printf_jobs(...) (indent(), fprintf(stderr, __VA_ARGS__))
642# define DEBUG_JOBS 1
643#else
644# define DEBUG_JOBS 0
645#endif
646
647#ifndef debug_printf_expand
648# define debug_printf_expand(...) (indent(), fprintf(stderr, __VA_ARGS__))
649# define DEBUG_EXPAND 1
650#else
651# define DEBUG_EXPAND 0
652#endif
653
654#ifndef debug_printf_glob
655# define debug_printf_glob(...) (indent(), fprintf(stderr, __VA_ARGS__))
656# define DEBUG_GLOB 1
657#else
658# define DEBUG_GLOB 0
659#endif
660
661#ifndef debug_printf_list
662# define debug_printf_list(...) (indent(), fprintf(stderr, __VA_ARGS__))
663#endif
664
665#ifndef debug_printf_subst
666# define debug_printf_subst(...) (indent(), fprintf(stderr, __VA_ARGS__))
667#endif
668
669#ifndef debug_printf_clean
670# define debug_printf_clean(...) (indent(), fprintf(stderr, __VA_ARGS__))
671# define DEBUG_CLEAN 1
672#else
673# define DEBUG_CLEAN 0
674#endif
675
676#if DEBUG_EXPAND
677static void debug_print_strings(const char *prefix, char **vv)
678{
679 indent();
680 fprintf(stderr, "%s:\n", prefix);
681 while (*vv)
682 fprintf(stderr, " '%s'\n", *vv++);
683}
684#else
685#define debug_print_strings(prefix, vv) ((void)0)
686#endif
687
688
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000689/* Leak hunting. Use hush_leaktool.sh for post-processing.
690 */
691#if LEAK_HUNTING
692static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000693{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000694 void *ptr = xmalloc((size + 0xff) & ~0xff);
695 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
696 return ptr;
697}
698static void *xxrealloc(int lineno, void *ptr, size_t size)
699{
700 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
701 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
702 return ptr;
703}
704static char *xxstrdup(int lineno, const char *str)
705{
706 char *ptr = xstrdup(str);
707 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
708 return ptr;
709}
710static void xxfree(void *ptr)
711{
712 fdprintf(2, "free %p\n", ptr);
713 free(ptr);
714}
715#define xmalloc(s) xxmalloc(__LINE__, s)
716#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
717#define xstrdup(s) xxstrdup(__LINE__, s)
718#define free(p) xxfree(p)
719#endif
720
721
722/* Syntax and runtime errors. They always abort scripts.
723 * In interactive use they usually discard unparsed and/or unexecuted commands
724 * and return to the prompt.
725 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
726 */
727#if HUSH_DEBUG < 2
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000728# define die_if_script(lineno, fmt...) die_if_script(fmt)
729# define syntax_error(lineno, msg) syntax_error(msg)
730# define syntax_error_at(lineno, msg) syntax_error_at(msg)
731# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
732# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
733# define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000734#endif
735
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000736static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000737{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000738 va_list p;
739
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000740#if HUSH_DEBUG >= 2
741 bb_error_msg("hush.c:%u", lineno);
742#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000743 va_start(p, fmt);
744 bb_verror_msg(fmt, p, NULL);
745 va_end(p);
746 if (!G_interactive_fd)
747 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000748}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000749
750static void syntax_error(unsigned lineno, const char *msg)
751{
752 if (msg)
753 die_if_script(lineno, "syntax error: %s", msg);
754 else
755 die_if_script(lineno, "syntax error", NULL);
756}
757
758static void syntax_error_at(unsigned lineno, const char *msg)
759{
760 die_if_script(lineno, "syntax error at '%s'", msg);
761}
762
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000763/* It so happens that all such cases are totally fatal
764 * even if shell is interactive: EOF while looking for closing
765 * delimiter. There is nowhere to read stuff from after that,
766 * it's EOF! The only choice is to terminate.
767 */
768static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000769static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000770{
771 char msg[2];
772 msg[0] = ch;
773 msg[1] = '\0';
774 die_if_script(lineno, "syntax error: unterminated %s", msg);
Denis Vlasenko0b677d82009-04-10 13:49:10 +0000775 xfunc_die();
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000776}
777
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000778static void syntax_error_unterm_str(unsigned lineno, const char *s)
779{
780 die_if_script(lineno, "syntax error: unterminated %s", s);
781}
782
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000783static void syntax_error_unexpected_ch(unsigned lineno, char ch)
784{
785 char msg[2];
786 msg[0] = ch;
787 msg[1] = '\0';
788 die_if_script(lineno, "syntax error: unexpected %s", msg);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000789}
790
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000791#if HUSH_DEBUG < 2
792# undef die_if_script
793# undef syntax_error
794# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000795# undef syntax_error_unterm_ch
796# undef syntax_error_unterm_str
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000797# undef syntax_error_unexpected_ch
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000798#else
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +0000799# define die_if_script(fmt...) die_if_script(__LINE__, fmt)
800# define syntax_error(msg) syntax_error(__LINE__, msg)
801# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
802# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
803# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
804# define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000805#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000806
Denis Vlasenko552433b2009-04-04 19:29:21 +0000807
Mike Frysinger67c1c7b2009-04-24 06:26:18 +0000808#if ENABLE_HUSH_INTERACTIVE
809static void cmdedit_update_prompt(void);
810#else
811# define cmdedit_update_prompt()
812#endif
813
814
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000815/* Utility functions
816 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000817static int glob_needed(const char *s)
818{
819 while (*s) {
820 if (*s == '\\')
821 s++;
822 if (*s == '*' || *s == '[' || *s == '?')
823 return 1;
824 s++;
825 }
826 return 0;
827}
828
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000829static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000830{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000831 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000832 return 0;
833 s++;
834 while (isalnum(*s) || *s == '_')
835 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000836 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000837}
838
Denis Vlasenko55789c62008-06-18 16:30:42 +0000839/* Replace each \x with x in place, return ptr past NUL. */
840static char *unbackslash(char *src)
841{
842 char *dst = src;
843 while (1) {
844 if (*src == '\\')
845 src++;
846 if ((*dst++ = *src++) == '\0')
847 break;
848 }
849 return dst;
850}
851
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000852static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000853{
854 int i;
855 unsigned count1;
856 unsigned count2;
857 char **v;
858
859 v = strings;
860 count1 = 0;
861 if (v) {
862 while (*v) {
863 count1++;
864 v++;
865 }
866 }
867 count2 = 0;
868 v = add;
869 while (*v) {
870 count2++;
871 v++;
872 }
873 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
874 v[count1 + count2] = NULL;
875 i = count2;
876 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000877 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000878 return v;
879}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000880#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000881static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
882{
883 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
884 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
885 return ptr;
886}
887#define add_strings_to_strings(strings, add, need_to_dup) \
888 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
889#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000890
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000891static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000892{
893 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000894 v[0] = add;
895 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000896 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000897}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000898#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000899static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
900{
901 char **ptr = add_string_to_strings(strings, add);
902 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
903 return ptr;
904}
905#define add_string_to_strings(strings, add) \
906 xx_add_string_to_strings(__LINE__, strings, add)
907#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000908
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000909static void putenv_all(char **strings)
910{
911 if (!strings)
912 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000913 while (*strings) {
914 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000915 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000916 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000917}
918
919static char **putenv_all_and_save_old(char **strings)
920{
921 char **old = NULL;
922 char **s = strings;
923
924 if (!strings)
925 return old;
926 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000927 char *v, *eq;
928
929 eq = strchr(*strings, '=');
930 if (eq) {
931 *eq = '\0';
932 v = getenv(*strings);
933 *eq = '=';
934 if (v) {
935 /* v points to VAL in VAR=VAL, go back to VAR */
936 v -= (eq - *strings) + 1;
937 old = add_string_to_strings(old, v);
938 }
939 }
940 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000941 }
942 putenv_all(s);
943 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000944}
945
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000946static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000947{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000948 char **v;
949
950 if (!strings)
951 return;
952
953 v = strings;
954 while (*v) {
955 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000956 debug_printf_env("unsetenv '%s'\n", *v);
957 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000958 }
959 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000960 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000961 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000962}
963
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000964static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000965{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000966 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000967}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000968
969
Denis Vlasenko270b1c32009-04-17 18:54:50 +0000970/* Helpers for setting new $n and restoring them back
971 */
972typedef struct save_arg_t {
973 char *sv_argv0;
974 char **sv_g_argv;
975 int sv_g_argc;
976 smallint sv_g_malloced;
977} save_arg_t;
978
979static void save_and_replace_G_args(save_arg_t *sv, char **argv)
980{
981 int n;
982
983 sv->sv_argv0 = argv[0];
984 sv->sv_g_argv = G.global_argv;
985 sv->sv_g_argc = G.global_argc;
986 sv->sv_g_malloced = G.global_args_malloced;
987
988 argv[0] = G.global_argv[0]; /* retain $0 */
989 G.global_argv = argv;
990 G.global_args_malloced = 0;
991
992 n = 1;
993 while (*++argv)
994 n++;
995 G.global_argc = n;
996}
997
998static void restore_G_args(save_arg_t *sv, char **argv)
999{
1000 char **pp;
1001
1002 if (G.global_args_malloced) {
1003 /* someone ran "set -- arg1 arg2 ...", undo */
1004 pp = G.global_argv;
1005 while (*++pp) /* note: does not free $0 */
1006 free(*pp);
1007 free(G.global_argv);
1008 }
1009 argv[0] = sv->sv_argv0;
1010 G.global_argv = sv->sv_g_argv;
1011 G.global_argc = sv->sv_g_argc;
1012 G.global_args_malloced = sv->sv_g_malloced;
1013}
1014
1015
Denis Vlasenkod5762932009-03-31 11:22:57 +00001016/* Basic theory of signal handling in shell
1017 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001018 * This does not describe what hush does, rather, it is current understanding
1019 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001020 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1021 *
1022 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1023 * is finished or backgrounded. It is the same in interactive and
1024 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001025 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001026 * ^C or ^Z from keyboard seem to execute "at once" because it usually
1027 * backgrounds (i.e. stops) or kills all members of currently running
1028 * pipe.
1029 *
1030 * Wait builtin in interruptible by signals for which user trap is set
1031 * or by SIGINT in interactive shell.
1032 *
1033 * Trap handlers will execute even within trap handlers. (right?)
1034 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001035 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001036 *
1037 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001038 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001039 *
1040 * Commands run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001041 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001042 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001043 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
1044 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001045 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001046 * Siganls which differ from SIG_DFL action
1047 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +00001048 *
1049 * SIGQUIT: ignore
1050 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001051 * SIGHUP (interactive):
1052 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +00001053 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00001054 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1055 * that all pipe members are stopped. Try this in bash:
1056 * while :; do :; done - ^Z does not background it
1057 * (while :; do :; done) - ^Z backgrounds it
Denis Vlasenkod5762932009-03-31 11:22:57 +00001058 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001059 * of the command line, show prompt. NB: ^C does not send SIGINT
1060 * to interactive shell while shell is waiting for a pipe,
1061 * since shell is bg'ed (is not in foreground process group).
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001062 * Example 1: this waits 5 sec, but does not execute ls:
1063 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1064 * Example 2: this does not wait and does not execute ls:
1065 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1066 * Example 3: this does not wait 5 sec, but executes ls:
1067 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +00001068 *
1069 * (What happens to signals which are IGN on shell start?)
1070 * (What happens with signal mask on shell start?)
1071 *
1072 * Implementation in hush
1073 * ======================
1074 * We use in-kernel pending signal mask to determine which signals were sent.
1075 * We block all signals which we don't want to take action immediately,
1076 * i.e. we block all signals which need to have special handling as described
1077 * above, and all signals which have traps set.
1078 * After each pipe execution, we extract any pending signals via sigtimedwait()
1079 * and act on them.
1080 *
1081 * unsigned non_DFL_mask: a mask of such "special" signals
1082 * sigset_t blocked_set: current blocked signal set
1083 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001084 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +00001085 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001086 * "trap 'cmd' SIGxxx":
1087 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +00001088 * after [v]fork, if we plan to be a shell:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001089 * unblock signals with special interactive handling
1090 * (child shell is not interactive),
1091 * unset all traps (note: regardless of child shell's type - {}, (), etc)
Denis Vlasenkod5762932009-03-31 11:22:57 +00001092 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001093 * POSIX says pending signal mask is cleared in child - no need to clear it.
1094 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001095 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001096 * Note: as a result, we do not use signal handlers much. The only uses
1097 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
1098 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +00001099 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001100enum {
1101 SPECIAL_INTERACTIVE_SIGS = 0
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001102 | (1 << SIGTERM)
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001103 | (1 << SIGINT)
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001104 | (1 << SIGHUP)
1105 ,
1106#if ENABLE_HUSH_JOB
1107 SPECIAL_JOB_SIGS = 0
1108 | (1 << SIGTTIN)
1109 | (1 << SIGTTOU)
1110 | (1 << SIGTSTP)
1111#endif
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00001112};
Denis Vlasenkod5762932009-03-31 11:22:57 +00001113
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001114//static void SIGCHLD_handler(int sig UNUSED_PARAM)
1115//{
1116// G.count_SIGCHLD++;
1117//}
1118
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001119#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001120
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001121/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1122#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001123/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001124#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1125
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001126/* Restores tty foreground process group, and exits.
1127 * May be called as signal handler for fatal signal
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001128 * (will resend signal to itself, producing correct exit state)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001129 * or called directly with -EXITCODE.
1130 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001131static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001132static void sigexit(int sig)
1133{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001134 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001135 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001136
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001137 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001138 * tty pgrp then, only top-level shell process does that */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00001139 if (G.saved_tty_pgrp && getpid() == G.root_pid)
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001140 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001141
1142 /* Not a signal, just exit */
1143 if (sig <= 0)
1144 _exit(- sig);
1145
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001146 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001147}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001148#else
1149
1150#define disable_restore_tty_pgrp_on_exit() ((void)0)
1151#define enable_restore_tty_pgrp_on_exit() ((void)0)
1152
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001153#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001154
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001155/* Restores tty foreground process group, and exits. */
1156static void hush_exit(int exitcode) NORETURN;
1157static void hush_exit(int exitcode)
1158{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001159 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1160 /* Prevent recursion:
1161 * trap "echo Hi; exit" EXIT; exit
1162 */
1163 char *argv[] = { NULL, G.traps[0], NULL };
1164 G.traps[0] = NULL;
1165 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001166 builtin_eval(argv);
1167 free(argv[1]);
1168 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001169
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001170#if ENABLE_HUSH_JOB
1171 fflush(NULL); /* flush all streams */
1172 sigexit(- (exitcode & 0xff));
1173#else
1174 exit(exitcode);
1175#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001176}
1177
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001178static int check_and_run_traps(int sig)
1179{
1180 static const struct timespec zero_timespec = { 0, 0 };
1181 smalluint save_rcode;
1182 int last_sig = 0;
1183
1184 if (sig)
1185 goto jump_in;
1186 while (1) {
1187 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1188 if (sig <= 0)
1189 break;
1190 jump_in:
1191 last_sig = sig;
1192 if (G.traps && G.traps[sig]) {
1193 if (G.traps[sig][0]) {
1194 /* We have user-defined handler */
1195 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1196 save_rcode = G.last_exitcode;
1197 builtin_eval(argv);
1198 free(argv[1]);
1199 G.last_exitcode = save_rcode;
1200 } /* else: "" trap, ignoring signal */
1201 continue;
1202 }
1203 /* not a trap: special action */
1204 switch (sig) {
1205// case SIGCHLD:
1206// G.count_SIGCHLD++;
1207// break;
1208 case SIGINT:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00001209 /* Builtin was ^C'ed, make it look prettier: */
1210 bb_putchar('\n');
1211 G.flag_SIGINT = 1;
1212 break;
1213#if ENABLE_HUSH_JOB
1214 case SIGHUP: {
1215 struct pipe *job;
1216 /* bash is observed to signal whole process groups,
1217 * not individual processes */
1218 for (job = G.job_list; job; job = job->next) {
1219 if (job->pgrp <= 0)
1220 continue;
1221 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1222 if (kill(- job->pgrp, SIGHUP) == 0)
1223 kill(- job->pgrp, SIGCONT);
1224 }
1225 sigexit(SIGHUP);
1226 }
1227#endif
1228 default: /* ignored: */
1229 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1230 break;
1231 }
1232 }
1233 return last_sig;
1234}
1235
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001236
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001237static const char *set_cwd(void)
1238{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001239 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1240 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001241 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001242 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001243 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1244 if (!G.cwd)
1245 G.cwd = bb_msg_unknown;
1246 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001247}
1248
Denis Vlasenko83506862007-11-23 13:11:42 +00001249
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001250/* Get/check local shell variables */
1251static struct variable *get_local_var(const char *name)
1252{
1253 struct variable *cur;
1254 int len;
1255
1256 if (!name)
1257 return NULL;
1258 len = strlen(name);
1259 for (cur = G.top_var; cur; cur = cur->next) {
1260 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1261 return cur;
1262 }
1263 return NULL;
1264}
1265
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001266static const char *get_local_var_value(const char *src)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001267{
1268 struct variable *var = get_local_var(src);
1269 if (var)
1270 return strchr(var->varstr, '=') + 1;
1271 return NULL;
1272}
1273
1274/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001275 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001276 * flg_export:
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001277 * 0: do not change export flag
1278 * (if creating new variable, flag will be 0)
1279 * 1: set export flag and putenv the variable
1280 * -1: clear export flag and unsetenv the variable
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001281 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001282 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001283#if BB_MMU
1284#define set_local_var(str, flg_export, flg_read_only) \
1285 set_local_var(str, flg_export)
1286#endif
1287static int set_local_var(char *str, int flg_export, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001288{
1289 struct variable *cur;
Denis Vlasenko950bd722009-04-21 11:23:56 +00001290 char *eq_sign;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001291 int name_len;
1292
Denis Vlasenko950bd722009-04-21 11:23:56 +00001293 eq_sign = strchr(str, '=');
1294 if (!eq_sign) { /* not expected to ever happen? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001295 free(str);
1296 return -1;
1297 }
1298
Denis Vlasenko950bd722009-04-21 11:23:56 +00001299 name_len = eq_sign - str + 1; /* including '=' */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001300 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1301 while (1) {
1302 if (strncmp(cur->varstr, str, name_len) != 0) {
1303 if (!cur->next) {
1304 /* Bail out. Note that now cur points
1305 * to last var in linked list */
1306 break;
1307 }
1308 cur = cur->next;
1309 continue;
1310 }
1311 /* We found an existing var with this name */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001312 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001313#if !BB_MMU
1314 if (!flg_read_only)
1315#endif
1316 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001317 free(str);
1318 return -1;
1319 }
Denis Vlasenko950bd722009-04-21 11:23:56 +00001320 if (flg_export == -1) {
1321 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1322 *eq_sign = '\0';
1323 unsetenv(str);
1324 *eq_sign = '=';
1325 }
1326 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001327 free_and_exp:
1328 free(str);
1329 goto exp;
1330 }
1331 if (cur->max_len >= strlen(str)) {
1332 /* This one is from startup env, reuse space */
1333 strcpy(cur->varstr, str);
1334 goto free_and_exp;
1335 }
1336 /* max_len == 0 signifies "malloced" var, which we can
1337 * (and has to) free */
1338 if (!cur->max_len)
1339 free(cur->varstr);
1340 cur->max_len = 0;
1341 goto set_str_and_exp;
1342 }
1343
1344 /* Not found - create next variable struct */
1345 cur->next = xzalloc(sizeof(*cur));
1346 cur = cur->next;
1347
1348 set_str_and_exp:
1349 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001350#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001351 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001352#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001353 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001354 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001355 cur->flg_export = 1;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001356 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1357 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001358 if (cur->flg_export) {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00001359 if (flg_export == -1) {
1360 cur->flg_export = 0;
1361 /* unsetenv was already done */
1362 } else {
1363 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1364 return putenv(cur->varstr);
1365 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001366 }
1367 return 0;
1368}
1369
Mike Frysingerd690f682009-03-30 06:50:54 +00001370static int unset_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001371{
1372 struct variable *cur;
1373 struct variable *prev = prev; /* for gcc */
1374 int name_len;
1375
1376 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001377 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001378 name_len = strlen(name);
1379 cur = G.top_var;
1380 while (cur) {
1381 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1382 if (cur->flg_read_only) {
1383 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001384 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001385 }
1386 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1387 * is ro, and we cannot reach this code on the 1st pass */
1388 prev->next = cur->next;
1389 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1390 bb_unsetenv(cur->varstr);
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001391 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1392 cmdedit_update_prompt();
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001393 if (!cur->max_len)
1394 free(cur->varstr);
1395 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001396 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001397 }
1398 prev = cur;
1399 cur = cur->next;
1400 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001401 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001402}
1403
Mike Frysinger98c52642009-04-02 10:02:37 +00001404#if ENABLE_SH_MATH_SUPPORT
1405#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1406#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1407static char *endofname(const char *name)
1408{
1409 char *p;
1410
1411 p = (char *) name;
1412 if (!is_name(*p))
1413 return p;
1414 while (*++p) {
1415 if (!is_in_name(*p))
1416 break;
1417 }
1418 return p;
1419}
1420
1421static void arith_set_local_var(const char *name, const char *val, int flags)
1422{
1423 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001424 char *var = xasprintf("%s=%s", name, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001425 set_local_var(var, flags, 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001426}
1427#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001428
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001429
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001430/*
1431 * in_str support
1432 */
1433static int static_get(struct in_str *i)
1434{
1435 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001436 if (ch != '\0')
1437 return ch;
1438 i->p--;
1439 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001440}
1441
1442static int static_peek(struct in_str *i)
1443{
1444 return *i->p;
1445}
1446
1447#if ENABLE_HUSH_INTERACTIVE
1448
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001449static void cmdedit_update_prompt(void)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001450{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001451 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001452 G.PS1 = get_local_var_value("PS1");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001453 if (G.PS1 == NULL)
1454 G.PS1 = "\\w \\$ ";
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001455 G.PS2 = get_local_var_value("PS2");
Mike Frysingerec2c6552009-03-28 12:24:44 +00001456 } else
1457 G.PS1 = NULL;
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00001458 if (G.PS2 == NULL)
1459 G.PS2 = "> ";
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001460}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001461
1462static const char* setup_prompt_string(int promptmode)
1463{
1464 const char *prompt_str;
1465 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001466 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1467 /* Set up the prompt */
1468 if (promptmode == 0) { /* PS1 */
1469 free((char*)G.PS1);
1470 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1471 prompt_str = G.PS1;
1472 } else
1473 prompt_str = G.PS2;
1474 } else
1475 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001476 debug_printf("result '%s'\n", prompt_str);
1477 return prompt_str;
1478}
1479
1480static void get_user_input(struct in_str *i)
1481{
1482 int r;
1483 const char *prompt_str;
1484
1485 prompt_str = setup_prompt_string(i->promptmode);
1486#if ENABLE_FEATURE_EDITING
1487 /* Enable command line editing only while a command line
1488 * is actually being read */
1489 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001490 G.flag_SIGINT = 0;
1491 /* buglet: SIGINT will not make new prompt to appear _at once_,
1492 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001493 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001494 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001495 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001496 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001497 i->eof_flag = (r < 0);
1498 if (i->eof_flag) { /* EOF/error detected */
1499 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1500 G.user_input_buf[1] = '\0';
1501 }
1502#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001503 do {
1504 G.flag_SIGINT = 0;
1505 fputs(prompt_str, stdout);
1506 fflush(stdout);
1507 G.user_input_buf[0] = r = fgetc(i->file);
1508 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001509//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001510 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001511 i->eof_flag = (r == EOF);
1512#endif
1513 i->p = G.user_input_buf;
1514}
1515
1516#endif /* INTERACTIVE */
1517
1518/* This is the magic location that prints prompts
1519 * and gets data back from the user */
1520static int file_get(struct in_str *i)
1521{
1522 int ch;
1523
1524 /* If there is data waiting, eat it up */
1525 if (i->p && *i->p) {
1526#if ENABLE_HUSH_INTERACTIVE
1527 take_cached:
1528#endif
1529 ch = *i->p++;
1530 if (i->eof_flag && !*i->p)
1531 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001532 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001533 } else {
1534 /* need to double check i->file because we might be doing something
1535 * more complicated by now, like sourcing or substituting. */
1536#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001537 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001538 do {
1539 get_user_input(i);
1540 } while (!*i->p); /* need non-empty line */
1541 i->promptmode = 1; /* PS2 */
1542 i->promptme = 0;
1543 goto take_cached;
1544 }
1545#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001546 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001547 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001548 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001549#if ENABLE_HUSH_INTERACTIVE
1550 if (ch == '\n')
1551 i->promptme = 1;
1552#endif
1553 return ch;
1554}
1555
Denis Vlasenko913a2012009-04-05 22:17:04 +00001556/* All callers guarantee this routine will never
1557 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001558 */
1559static int file_peek(struct in_str *i)
1560{
1561 int ch;
1562 if (i->p && *i->p) {
1563 if (i->eof_flag && !i->p[1])
1564 return EOF;
1565 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001566 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001567 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001568 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001569 i->eof_flag = (ch == EOF);
1570 i->peek_buf[0] = ch;
1571 i->peek_buf[1] = '\0';
1572 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001573 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001574 return ch;
1575}
1576
1577static void setup_file_in_str(struct in_str *i, FILE *f)
1578{
1579 i->peek = file_peek;
1580 i->get = file_get;
1581#if ENABLE_HUSH_INTERACTIVE
1582 i->promptme = 1;
1583 i->promptmode = 0; /* PS1 */
1584#endif
1585 i->file = f;
1586 i->p = NULL;
1587}
1588
1589static void setup_string_in_str(struct in_str *i, const char *s)
1590{
1591 i->peek = static_peek;
1592 i->get = static_get;
1593#if ENABLE_HUSH_INTERACTIVE
1594 i->promptme = 1;
1595 i->promptmode = 0; /* PS1 */
1596#endif
1597 i->p = s;
1598 i->eof_flag = 0;
1599}
1600
1601
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001602/*
1603 * o_string support
1604 */
1605#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001606
Denis Vlasenko0b677d82009-04-10 13:49:10 +00001607static void o_reset_to_empty_unquoted(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001608{
1609 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001610 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001611 if (o->data)
1612 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001613}
1614
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001615static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001616{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001617 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001618 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001619}
1620
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001621static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1622{
1623 free(o->data);
1624}
1625
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001626static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001627{
1628 if (o->length + len > o->maxlen) {
1629 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1630 o->data = xrealloc(o->data, 1 + o->maxlen);
1631 }
1632}
1633
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001634static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001635{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001636 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1637 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001638 o->data[o->length] = ch;
1639 o->length++;
1640 o->data[o->length] = '\0';
1641}
1642
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001643static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001644{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001645 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001646 memcpy(&o->data[o->length], str, len);
1647 o->length += len;
1648 o->data[o->length] = '\0';
1649}
1650
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001651#if !BB_MMU
1652static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001653{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001654 o_addblock(o, str, strlen(str));
1655}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001656static void nommu_addchr(o_string *o, int ch)
1657{
1658 if (o)
1659 o_addchr(o, ch);
1660}
1661#else
1662#define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001663#endif
1664
1665static void o_addstr_with_NUL(o_string *o, const char *str)
1666{
1667 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001668}
1669
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001670static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001671{
1672 while (len) {
1673 o_addchr(o, *str);
1674 if (*str++ == '\\'
1675 && (*str != '*' && *str != '?' && *str != '[')
1676 ) {
1677 o_addchr(o, '\\');
1678 }
1679 len--;
1680 }
1681}
1682
Eric Andersen25f27032001-04-26 23:22:31 +00001683/* My analysis of quoting semantics tells me that state information
1684 * is associated with a destination, not a source.
1685 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001686static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001687{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001688 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001689 char *found = strchr("*?[\\", ch);
1690 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001691 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001692 o_grow_by(o, sz);
1693 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001694 o->data[o->length] = '\\';
1695 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001696 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001697 o->data[o->length] = ch;
1698 o->length++;
1699 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001700}
1701
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001702static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001703{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001704 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001705 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001706 sz++;
1707 o->data[o->length] = '\\';
1708 o->length++;
1709 }
1710 o_grow_by(o, sz);
1711 o->data[o->length] = ch;
1712 o->length++;
1713 o->data[o->length] = '\0';
1714}
1715
1716static void o_addQstr(o_string *o, const char *str, int len)
1717{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001718 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001719 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001720 return;
1721 }
1722 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001723 char ch;
1724 int sz;
1725 int ordinary_cnt = strcspn(str, "*?[\\");
1726 if (ordinary_cnt > len) /* paranoia */
1727 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001728 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001729 if (ordinary_cnt == len)
1730 return;
1731 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001732 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001733
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001734 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001735 sz = 1;
1736 if (ch) { /* it is necessarily one of "*?[\\" */
1737 sz++;
1738 o->data[o->length] = '\\';
1739 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001740 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001741 o_grow_by(o, sz);
1742 o->data[o->length] = ch;
1743 o->length++;
1744 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001745 }
1746}
1747
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001748/* A special kind of o_string for $VAR and `cmd` expansion.
1749 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001750 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001751 * list[i] contains an INDEX (int!) into this string data.
1752 * It means that if list[] needs to grow, data needs to be moved higher up
1753 * but list[i]'s need not be modified.
1754 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001755 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001756 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1757 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001758#if DEBUG_EXPAND || DEBUG_GLOB
1759static void debug_print_list(const char *prefix, o_string *o, int n)
1760{
1761 char **list = (char**)o->data;
1762 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1763 int i = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001764
1765 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001766 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1767 prefix, list, n, string_start, o->length, o->maxlen);
1768 while (i < n) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001769 indent();
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001770 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1771 o->data + (int)list[i] + string_start,
1772 o->data + (int)list[i] + string_start);
1773 i++;
1774 }
1775 if (n) {
1776 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00001777 indent();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001778 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001779 }
1780}
1781#else
1782#define debug_print_list(prefix, o, n) ((void)0)
1783#endif
1784
1785/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1786 * in list[n] so that it points past last stored byte so far.
1787 * It returns n+1. */
1788static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001789{
1790 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001791 int string_start;
1792 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001793
1794 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001795 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1796 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001797 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001798 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001799 /* list[n] points to string_start, make space for 16 more pointers */
1800 o->maxlen += 0x10 * sizeof(list[0]);
1801 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001802 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001803 memmove(list + n + 0x10, list + n, string_len);
1804 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001805 } else {
1806 debug_printf_list("list[%d]=%d string_start=%d\n",
1807 n, string_len, string_start);
1808 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001809 } else {
1810 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001811 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1812 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001813 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1814 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001815 o->has_empty_slot = 0;
1816 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001817 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001818 return n + 1;
1819}
1820
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001821/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001822static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001823{
1824 char **list = (char**)o->data;
1825 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1826
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001827 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001828}
1829
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001830/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001831 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001832static int o_glob(o_string *o, int n)
1833{
1834 glob_t globdata;
1835 int gr;
1836 char *pattern;
1837
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001838 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001839 if (!o->data)
1840 return o_save_ptr_helper(o, n);
1841 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001842 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001843 if (!glob_needed(pattern)) {
1844 literal:
1845 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001846 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001847 return o_save_ptr_helper(o, n);
1848 }
1849
1850 memset(&globdata, 0, sizeof(globdata));
1851 gr = glob(pattern, 0, NULL, &globdata);
1852 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1853 if (gr == GLOB_NOSPACE)
1854 bb_error_msg_and_die("out of memory during glob");
1855 if (gr == GLOB_NOMATCH) {
1856 globfree(&globdata);
1857 goto literal;
1858 }
1859 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00001860 /* TODO: testcase for bad glob pattern behavior */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001861 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1862 }
1863 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1864 char **argv = globdata.gl_pathv;
1865 o->length = pattern - o->data; /* "forget" pattern */
1866 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001867 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001868 n = o_save_ptr_helper(o, n);
1869 argv++;
1870 if (!*argv)
1871 break;
1872 }
1873 }
1874 globfree(&globdata);
1875 if (DEBUG_GLOB)
1876 debug_print_list("o_glob returning", o, n);
1877 return n;
1878}
1879
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001880/* If o->o_glob == 1, glob the string so far remembered.
1881 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001882static int o_save_ptr(o_string *o, int n)
1883{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001884 if (o->o_glob) { /* if globbing is requested */
1885 /* If o->has_empty_slot, list[n] was already globbed
1886 * (if it was requested back then when it was filled)
1887 * so don't do that again! */
1888 if (!o->has_empty_slot)
1889 return o_glob(o, n); /* o_save_ptr_helper is inside */
1890 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001891 return o_save_ptr_helper(o, n);
1892}
1893
1894/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001895static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001896{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001897 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001898 int string_start;
1899
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001900 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1901 if (DEBUG_EXPAND)
1902 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001903 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001904 list = (char**)o->data;
1905 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1906 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001907 while (n) {
1908 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001909 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001910 }
1911 return list;
1912}
1913
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001914
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001915/* Expansion can recurse */
1916#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001917static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001918#endif
1919static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001920#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001921#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001922 parse_stream_dquoted(dest, input, dquote_end)
1923#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001924static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001925 o_string *dest,
1926 struct in_str *input,
1927 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001928
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001929/* expand_strvec_to_strvec() takes a list of strings, expands
1930 * all variable references within and returns a pointer to
1931 * a list of expanded strings, possibly with larger number
1932 * of strings. (Think VAR="a b"; echo $VAR).
1933 * This new list is allocated as a single malloc block.
1934 * NULL-terminated list of char* pointers is at the beginning of it,
1935 * followed by strings themself.
1936 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001937
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001938/* Store given string, finalizing the word and starting new one whenever
1939 * we encounter IFS char(s). This is used for expanding variable values.
1940 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1941static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001942{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001943 while (1) {
1944 int word_len = strcspn(str, G.ifs);
1945 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001946 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001947 o_addQstr(output, str, word_len);
1948 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001949 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001950 str += word_len;
1951 }
1952 if (!*str) /* EOL - do not finalize word */
1953 break;
1954 o_addchr(output, '\0');
1955 debug_print_list("expand_on_ifs", output, n);
1956 n = o_save_ptr(output, n);
1957 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001958 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001959 debug_print_list("expand_on_ifs[1]", output, n);
1960 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001961}
1962
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001963/* Helper to expand $((...)) and heredoc body. These act as if
1964 * they are in double quotes, with the exception that they are not :).
1965 * Just the rules are similar: "expand only $var and `cmd`"
1966 *
1967 * Returns malloced string.
1968 * As an optimization, we return NULL if expansion is not needed.
1969 */
1970static char *expand_pseudo_dquoted(const char *str)
1971{
1972 char *exp_str;
1973 struct in_str input;
1974 o_string dest = NULL_O_STRING;
1975
1976 if (strchr(str, '$') == NULL
1977#if ENABLE_HUSH_TICK
1978 && strchr(str, '`') == NULL
1979#endif
1980 ) {
1981 return NULL;
1982 }
1983
1984 /* We need to expand. Example:
1985 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1986 */
1987 setup_string_in_str(&input, str);
1988 parse_stream_dquoted(NULL, &dest, &input, EOF);
1989 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1990 exp_str = expand_string_to_string(dest.data);
1991 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1992 o_free_unsafe(&dest);
1993 return exp_str;
1994}
1995
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001996/* Expand all variable references in given string, adding words to list[]
1997 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1998 * to be filled). This routine is extremely tricky: has to deal with
1999 * variables/parameters with whitespace, $* and $@, and constructs like
2000 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2001static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002002{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002003 /* or_mask is either 0 (normal case) or 0x80
2004 * (expansion of right-hand side of assignment == 1-element expand.
2005 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00002006
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002007 char ored_ch;
2008 char *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002009
2010 ored_ch = 0;
2011
2012 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2013 debug_print_list("expand_vars_to_list", output, n);
2014 n = o_save_ptr(output, n);
2015 debug_print_list("expand_vars_to_list[0]", output, n);
2016
2017 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002018 char first_ch;
2019 int i;
2020 char *dyn_val = NULL;
2021 const char *val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002022#if ENABLE_HUSH_TICK
2023 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002024#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002025#if ENABLE_SH_MATH_SUPPORT
2026 char arith_buf[sizeof(arith_t)*3 + 2];
2027#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002028 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002029 debug_print_list("expand_vars_to_list[1]", output, n);
2030 arg = ++p;
2031 p = strchr(p, SPECIAL_VAR_SYMBOL);
2032
2033 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2034 /* "$@" is special. Even if quoted, it can still
2035 * expand to nothing (not even an empty string) */
2036 if ((first_ch & 0x7f) != '@')
2037 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002038
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002039 switch (first_ch & 0x7f) {
2040 /* Highest bit in first_ch indicates that var is double-quoted */
2041 case '$': /* pid */
2042 val = utoa(G.root_pid);
2043 break;
2044 case '!': /* bg pid */
2045 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2046 break;
2047 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00002048 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002049 break;
2050 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002051 if (arg[1] != SPECIAL_VAR_SYMBOL)
2052 /* actually, it's a ${#var} */
2053 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002054 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2055 break;
2056 case '*':
2057 case '@':
2058 i = 1;
2059 if (!G.global_argv[i])
2060 break;
2061 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2062 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002063 smallint sv = output->o_escape;
2064 /* unquoted var's contents should be globbed, so don't escape */
2065 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002066 while (G.global_argv[i]) {
2067 n = expand_on_ifs(output, n, G.global_argv[i]);
2068 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2069 if (G.global_argv[i++][0] && G.global_argv[i]) {
2070 /* this argv[] is not empty and not last:
2071 * put terminating NUL, start new word */
2072 o_addchr(output, '\0');
2073 debug_print_list("expand_vars_to_list[2]", output, n);
2074 n = o_save_ptr(output, n);
2075 debug_print_list("expand_vars_to_list[3]", output, n);
2076 }
2077 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002078 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002079 } else
2080 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2081 * and in this case should treat it like '$*' - see 'else...' below */
2082 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2083 while (1) {
2084 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2085 if (++i >= G.global_argc)
2086 break;
2087 o_addchr(output, '\0');
2088 debug_print_list("expand_vars_to_list[4]", output, n);
2089 n = o_save_ptr(output, n);
2090 }
2091 } else { /* quoted $*: add as one word */
2092 while (1) {
2093 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2094 if (!G.global_argv[++i])
2095 break;
2096 if (G.ifs[0])
2097 o_addchr(output, G.ifs[0]);
2098 }
2099 }
2100 break;
2101 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2102 /* "Empty variable", used to make "" etc to not disappear */
2103 arg++;
2104 ored_ch = 0x80;
2105 break;
2106#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002107 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 *p = '\0';
2109 arg++;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002110 /* Can't just stuff it into output o_string,
2111 * expanded result may need to be globbed
2112 * and $IFS-splitted */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002113 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00002114 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2116 val = subst_result.data;
2117 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00002118#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00002119#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002120 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002121 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00002122 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00002123 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002124 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002125
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002126 arg++; /* skip '+' */
2127 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00002128 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002129
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002130 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002131 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002132 hooks.setvar = arith_set_local_var;
2133 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002134 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
2135 free(exp_str);
2136
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002137 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002138 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00002139 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002140 case -3:
2141 msg = "exponent less than 0";
2142 break;
2143 case -2:
2144 msg = "divide by 0";
2145 break;
2146 case -5:
2147 msg = "expression recursion loop detected";
2148 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00002149 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002150 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00002151 }
Mike Frysinger98c52642009-04-02 10:02:37 +00002152 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002153 sprintf(arith_buf, arith_t_fmt, res);
2154 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00002155 break;
2156 }
2157#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002158 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002159 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002160 bool exp_len = false;
2161 bool exp_null = false;
2162 char *var = arg;
2163 char exp_save = exp_save; /* for compiler */
2164 char exp_op = exp_op; /* for compiler */
2165 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002166 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00002167
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168 *p = '\0';
2169 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002170
2171 /* prepare for expansions */
2172 if (var[0] == '#') {
2173 /* handle length expansion ${#var} */
2174 exp_len = true;
2175 ++var;
2176 } else {
2177 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002178 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002179 if (!var[exp_off])
2180 exp_off = 0;
2181 if (exp_off) {
2182 exp_save = var[exp_off];
2183 exp_null = exp_save == ':';
2184 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002185 if (exp_null)
2186 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002187 exp_op = *exp_word++;
2188 var[exp_off] = '\0';
2189 }
2190 }
2191
2192 /* lookup the variable in question */
2193 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002194 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002195 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002196 if (i < G.global_argc)
2197 val = G.global_argv[i];
2198 /* else val remains NULL: $N with too big N */
2199 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002200 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002201
2202 /* handle any expansions */
2203 if (exp_len) {
2204 debug_printf_expand("expand: length of '%s' = ", val);
2205 val = utoa(val ? strlen(val) : 0);
2206 debug_printf_expand("%s\n", val);
2207 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002208 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002209 if (val) {
2210 /* we need to do a pattern match */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002211 bool match_at_left;
Mike Frysinger57e74672009-04-09 23:00:33 +00002212 char *loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002213 scan_t scan = pick_scan(exp_op, *exp_word, &match_at_left);
Mike Frysinger57e74672009-04-09 23:00:33 +00002214 if (exp_op == *exp_word) /* ## or %% */
2215 ++exp_word;
2216 val = dyn_val = xstrdup(val);
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002217 loc = scan(dyn_val, exp_word, match_at_left);
2218 if (match_at_left) /* # or ## */
Mike Frysinger57e74672009-04-09 23:00:33 +00002219 val = loc;
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002220 else if (loc) /* % or %% and match was found */
Mike Frysinger57e74672009-04-09 23:00:33 +00002221 *loc = '\0';
2222 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002223 } else {
2224 /* we need to do an expansion */
2225 int exp_test = (!val || (exp_null && !val[0]));
2226 if (exp_op == '+')
2227 exp_test = !exp_test;
2228 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2229 exp_null ? "true" : "false", exp_test);
2230 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002231 if (exp_op == '?') {
2232//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002233 /* ${var?[error_msg_if_unset]} */
2234 /* ${var:?[error_msg_if_unset_or_null]} */
2235 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002236 die_if_script("%s: %s",
2237 var,
2238 exp_word[0] ? exp_word : "parameter null or not set"
2239 );
2240 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002241 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002242 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002243
Mike Frysingera4f331d2009-04-07 06:03:22 +00002244 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002245 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002246 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002247 /* mimic bash message */
2248 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002249 val = NULL;
2250 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002251 char *new_var = xasprintf("%s=%s", var, val);
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00002252 set_local_var(new_var, 0, 0);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002253 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002254 }
2255 }
2256 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002257
Mike Frysinger6379bb42009-03-28 18:55:03 +00002258 var[exp_off] = exp_save;
2259 }
2260
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002261 arg[0] = first_ch;
2262#if ENABLE_HUSH_TICK
2263 store_val:
2264#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002265 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002266 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002267 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002268 /* unquoted var's contents should be globbed, so don't escape */
2269 smallint sv = output->o_escape;
2270 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002271 n = expand_on_ifs(output, n, val);
2272 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002273 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002274 }
2275 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002276 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002277 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002278 } /* default: */
2279 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko5b7589e2009-04-26 11:25:19 +00002280
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002281 if (val) {
2282 o_addQstr(output, val, strlen(val));
2283 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002284 free(dyn_val);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002285 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002286 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002287 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002288
2289#if ENABLE_HUSH_TICK
2290 o_free(&subst_result);
2291#endif
2292 arg = ++p;
2293 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2294
2295 if (arg[0]) {
2296 debug_print_list("expand_vars_to_list[a]", output, n);
2297 /* this part is literal, and it was already pre-quoted
2298 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002299 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002300 debug_print_list("expand_vars_to_list[b]", output, n);
2301 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2302 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2303 ) {
2304 n--;
2305 /* allow to reuse list[n] later without re-growth */
2306 output->has_empty_slot = 1;
2307 } else {
2308 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002309 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002310 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002311}
2312
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002313static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002314{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002315 int n;
2316 char **list;
2317 char **v;
2318 o_string output = NULL_O_STRING;
2319
2320 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002321 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002322 /* (unquoted $var will temporarily switch it off) */
2323 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002324 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002325
2326 n = 0;
2327 v = argv;
2328 while (*v) {
2329 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2330 v++;
2331 }
2332 debug_print_list("expand_variables", &output, n);
2333
2334 /* output.data (malloced in one block) gets returned in "list" */
2335 list = o_finalize_list(&output, n);
2336 debug_print_strings("expand_variables[1]", list);
2337 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002338}
2339
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002340static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002341{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002342 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002343}
2344
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002345/* Used for expansion of right hand of assignments */
2346/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2347 * "v=/bin/c*" */
2348static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002349{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002350 char *argv[2], **list;
2351
2352 argv[0] = (char*)str;
2353 argv[1] = NULL;
2354 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2355 if (HUSH_DEBUG)
2356 if (!list[0] || list[1])
2357 bb_error_msg_and_die("BUG in varexp2");
2358 /* actually, just move string 2*sizeof(char*) bytes back */
2359 overlapping_strcpy((char*)list, list[0]);
2360 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2361 return (char*)list;
2362}
2363
2364/* Used for "eval" builtin */
2365static char* expand_strvec_to_string(char **argv)
2366{
2367 char **list;
2368
2369 list = expand_variables(argv, 0x80);
2370 /* Convert all NULs to spaces */
2371 if (list[0]) {
2372 int n = 1;
2373 while (list[n]) {
2374 if (HUSH_DEBUG)
2375 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2376 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00002377 /* bash uses ' ' regardless of $IFS contents */
2378 list[n][-1] = ' ';
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002379 n++;
2380 }
2381 }
2382 overlapping_strcpy((char*)list, list[0]);
2383 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2384 return (char*)list;
2385}
2386
2387static char **expand_assignments(char **argv, int count)
2388{
2389 int i;
2390 char **p = NULL;
2391 /* Expand assignments into one string each */
2392 for (i = 0; i < count; i++) {
2393 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2394 }
2395 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002396}
2397
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002398
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002399#if BB_MMU
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002400/* never called */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002401void re_execute_shell(char ***to_free, const char *s, char *argv0, char **argv);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002402
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002403static void reset_traps_to_defaults(void)
2404{
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002405 /* This function is always called in a child shell
2406 * after fork (not vfork, NOMMU doesn't use this function).
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002407 * Child shells are not interactive.
2408 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
2409 * Testcase: (while :; do :; done) + ^Z should background.
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002410 * Same goes for SIGTERM, SIGHUP, SIGINT.
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002411 */
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002412 unsigned sig;
2413 unsigned mask;
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002414
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002415 if (!G.traps && !(G.non_DFL_mask & SPECIAL_INTERACTIVE_SIGS))
2416 return;
2417
2418 /* Stupid. It can be done with *single* &= op, but we can't use
2419 * the fact that G.blocked_set is implemented as a bitmask... */
2420 mask = (SPECIAL_INTERACTIVE_SIGS >> 1);
2421 sig = 1;
2422 while (1) {
2423 if (mask & 1)
2424 sigdelset(&G.blocked_set, sig);
2425 mask >>= 1;
2426 if (!mask)
2427 break;
2428 sig++;
2429 }
2430
2431 G.non_DFL_mask &= ~SPECIAL_INTERACTIVE_SIGS;
2432 mask = G.non_DFL_mask;
2433 if (G.traps) for (sig = 0; sig < NSIG; sig++, mask >>= 1) {
2434 if (!G.traps[sig])
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002435 continue;
2436 free(G.traps[sig]);
2437 G.traps[sig] = NULL;
2438 /* There is no signal for 0 (EXIT) */
2439 if (sig == 0)
2440 continue;
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00002441 /* There was a trap handler, we are removing it.
2442 * But if sig still has non-DFL handling,
2443 * we should not unblock it. */
2444 if (mask & 1)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002445 continue;
2446 sigdelset(&G.blocked_set, sig);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002447 }
Denis Vlasenko74a931a2009-04-15 23:29:44 +00002448 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002449}
2450
2451#else /* !BB_MMU */
2452
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002453static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv) NORETURN;
2454static void re_execute_shell(char ***to_free, const char *s, char *g_argv0, char **g_argv)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002455{
2456 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002457 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002458 struct variable *cur;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002459#if ENABLE_HUSH_FUNCTIONS
2460 struct function *funcp;
2461#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002462 char **argv, **pp;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002463 unsigned cnt;
2464
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002465 if (!g_argv0) { /* heredoc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002466 argv = heredoc_argv;
2467 argv[0] = (char *) G.argv0_for_re_execing;
2468 argv[1] = (char *) "-<";
2469 argv[2] = (char *) s;
2470 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002471 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002472 goto do_exec;
2473 }
2474
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002475 sprintf(param_buf, "-$%x:%x:%x" IF_HUSH_LOOPS(":%x")
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002476 , (unsigned) G.root_pid
2477 , (unsigned) G.last_bg_pid
2478 , (unsigned) G.last_exitcode
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00002479 IF_HUSH_LOOPS(, G.depth_of_loop)
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002480 );
Denis Vlasenkobc569742009-04-12 20:35:19 +00002481 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...> <funcs...>
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002482 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002483 */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002484 cnt = 6;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002485 for (cur = G.top_var; cur; cur = cur->next) {
2486 if (!cur->flg_export || cur->flg_read_only)
2487 cnt += 2;
2488 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002489#if ENABLE_HUSH_FUNCTIONS
2490 for (funcp = G.top_func; funcp; funcp = funcp->next)
2491 cnt += 3;
2492#endif
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002493 pp = g_argv;
2494 while (*pp++)
2495 cnt++;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002496 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002497 *pp++ = (char *) G.argv0_for_re_execing;
2498 *pp++ = param_buf;
2499 for (cur = G.top_var; cur; cur = cur->next) {
2500 if (cur->varstr == hush_version_str)
2501 continue;
2502 if (cur->flg_read_only) {
2503 *pp++ = (char *) "-R";
2504 *pp++ = cur->varstr;
2505 } else if (!cur->flg_export) {
2506 *pp++ = (char *) "-V";
2507 *pp++ = cur->varstr;
2508 }
2509 }
Denis Vlasenkobc569742009-04-12 20:35:19 +00002510#if ENABLE_HUSH_FUNCTIONS
2511 for (funcp = G.top_func; funcp; funcp = funcp->next) {
2512 *pp++ = (char *) "-F";
2513 *pp++ = funcp->name;
2514 *pp++ = funcp->body_as_string;
2515 }
2516#endif
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002517 /* We can pass activated traps here. Say, -Tnn:trap_string
2518 *
2519 * However, POSIX says that subshells reset signals with traps
2520 * to SIG_DFL.
2521 * I tested bash-3.2 and it not only does that with true subshells
2522 * of the form ( list ), but with any forked children shells.
2523 * I set trap "echo W" WINCH; and then tried:
2524 *
2525 * { echo 1; sleep 20; echo 2; } &
2526 * while true; do echo 1; sleep 20; echo 2; break; done &
2527 * true | { echo 1; sleep 20; echo 2; } | cat
2528 *
2529 * In all these cases sending SIGWINCH to the child shell
2530 * did not run the trap. If I add trap "echo V" WINCH;
2531 * _inside_ group (just before echo 1), it works.
2532 *
2533 * I conclude it means we don't need to pass active traps here.
2534 * exec syscall below resets them to SIG_DFL for us.
2535 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002536 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002537 *pp++ = (char *) s;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002538 *pp++ = g_argv0;
2539 while (*g_argv)
2540 *pp++ = *g_argv++;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002541 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002542 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002543
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002544 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002545 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2546 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002547 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002548 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002549 if (argv[0][0] == '/')
2550 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002551 xfunc_error_retval = 127;
2552 bb_error_msg_and_die("can't re-execute the shell");
2553}
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002554#endif /* !BB_MMU */
2555
2556
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002557static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002558{
2559 struct fd_pair pair;
2560 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002561 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002562 /* the _body_ of heredoc (misleading field name) */
2563 const char *heredoc = redir->rd_filename;
2564 char *expanded;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002565#if !BB_MMU
2566 char **to_free;
2567#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002568
2569 expanded = NULL;
2570 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2571 expanded = expand_pseudo_dquoted(heredoc);
2572 if (expanded)
2573 heredoc = expanded;
2574 }
2575 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002576
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002577 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002578 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002579 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002580
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002581 /* Try writing without forking. Newer kernels have
2582 * dynamically growing pipes. Must use non-blocking write! */
2583 ndelay_on(pair.wr);
2584 while (1) {
2585 written = write(pair.wr, heredoc, len);
2586 if (written <= 0)
2587 break;
2588 len -= written;
2589 if (len == 0) {
2590 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002591 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002592 return;
2593 }
2594 heredoc += written;
2595 }
2596 ndelay_off(pair.wr);
2597
2598 /* Okay, pipe buffer was not big enough */
2599 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002600 * for the unsuspecting parent process. Child creates a grandchild
2601 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002602 * (that exec happens after we return from this function) */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002603#if !BB_MMU
2604 to_free = NULL;
2605#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002606 pid = vfork();
2607 if (pid < 0)
2608 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002609 if (pid == 0) {
2610 /* child */
Denis Vlasenko41ddecd2009-04-15 21:58:14 +00002611 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002612 pid = BB_MMU ? fork() : vfork();
2613 if (pid < 0)
2614 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2615 if (pid != 0)
2616 _exit(0);
2617 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002618 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002619#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002620 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002621 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002622#else
2623 /* Delegate blocking writes to another process */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002624 xmove_fd(pair.wr, STDOUT_FILENO);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002625 re_execute_shell(&to_free, heredoc, NULL, NULL);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002626#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002627 }
2628 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002629 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002630#if !BB_MMU
2631 free(to_free);
2632#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002633 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002634 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002635 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002636}
2637
Eric Andersen25f27032001-04-26 23:22:31 +00002638/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2639 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002640static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002641{
2642 int openfd, mode;
2643 struct redir_struct *redir;
2644
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002645 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002646 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002647 /* rd_fd<<HERE case */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002648 if (squirrel && redir->rd_fd < 3) {
2649 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002650 }
2651 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2652 * of the heredoc */
2653 debug_printf_parse("set heredoc '%s'\n",
2654 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002655 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002656 continue;
2657 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002658
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002659 if (redir->rd_dup == REDIRFD_TO_FILE) {
2660 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002661 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002662 if (redir->rd_filename == NULL) {
2663 /* Something went wrong in the parse.
2664 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002665 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002666 continue;
2667 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002668 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002669 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002670 openfd = open_or_warn(p, mode);
2671 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002672 if (openfd < 0) {
2673 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002674 * bash and ash both lose it as well (though zsh doesn't!) */
2675//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002676 return 1;
2677 }
2678 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002679 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002680 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002681 }
2682
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002683 if (openfd != redir->rd_fd) {
2684 if (squirrel && redir->rd_fd < 3) {
2685 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002686 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002687 if (openfd == REDIRFD_CLOSE) {
2688 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002689 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002690 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002691 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002692 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002693 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002694 }
Eric Andersen25f27032001-04-26 23:22:31 +00002695 }
2696 }
2697 return 0;
2698}
2699
2700static void restore_redirects(int squirrel[])
2701{
2702 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002703 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002704 fd = squirrel[i];
2705 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002706 /* We simply die on error */
2707 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002708 }
2709 }
2710}
2711
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002712
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002713static void free_pipe_list(struct pipe *head);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002714
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002715/* Return code is the exit status of the pipe */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002716static void free_pipe(struct pipe *pi)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002717{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002718 char **p;
2719 struct command *command;
2720 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002721 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002722
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002723 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002724 return;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002725 debug_printf_clean("run pipe: (pid %d)\n", getpid());
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002726 for (i = 0; i < pi->num_cmds; i++) {
2727 command = &pi->cmds[i];
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002728 debug_printf_clean(" command %d:\n", i);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002729 if (command->argv) {
2730 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002731 debug_printf_clean(" argv[%d] = %s\n", a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002732 }
2733 free_strings(command->argv);
2734 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002735 }
2736 /* not "else if": on syntax error, we may have both! */
2737 if (command->group) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002738 debug_printf_clean(" begin group (grp_type:%d)\n",
2739 command->grp_type);
2740 free_pipe_list(command->group);
2741 debug_printf_clean(" end group\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002742 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002743 }
Denis Vlasenkoed055212009-04-11 10:37:10 +00002744 /* else is crucial here.
2745 * If group != NULL, child_func is meaningless */
2746#if ENABLE_HUSH_FUNCTIONS
2747 else if (command->child_func) {
2748 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2749 command->child_func->parent_cmd = NULL;
2750 }
2751#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002752#if !BB_MMU
2753 free(command->group_as_string);
2754 command->group_as_string = NULL;
2755#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002756 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002757 debug_printf_clean(" redirect %d%s",
2758 r->rd_fd, redir_table[r->rd_type].descrip);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002759 /* guard against the case >$FOO, where foo is unset or blank */
2760 if (r->rd_filename) {
2761 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2762 free(r->rd_filename);
2763 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002764 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002765 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002766 rnext = r->next;
2767 free(r);
2768 }
2769 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002770 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002771 free(pi->cmds); /* children are an array, they get freed all at once */
2772 pi->cmds = NULL;
2773#if ENABLE_HUSH_JOB
2774 free(pi->cmdtext);
2775 pi->cmdtext = NULL;
2776#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002777}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002778
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002779static void free_pipe_list(struct pipe *head)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002780{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002781 struct pipe *pi, *next;
2782
2783 for (pi = head; pi; pi = next) {
2784#if HAS_KEYWORDS
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002785 debug_printf_clean(" pipe reserved word %d\n", pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002786#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00002787 free_pipe(pi);
2788 debug_printf_clean("pipe followup code %d\n", pi->followup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002789 next = pi->next;
2790 /*pi->next = NULL;*/
2791 free(pi);
2792 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002793}
2794
2795
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002796static int run_list(struct pipe *pi);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002797#if BB_MMU
2798#define parse_stream(pstring, input, end_trigger) \
2799 parse_stream(input, end_trigger)
2800#endif
2801static struct pipe *parse_stream(char **pstring,
2802 struct in_str *input,
2803 int end_trigger);
2804static void parse_and_run_string(const char *s);
2805
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002806
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002807static const struct built_in_command* find_builtin(const char *name)
2808{
2809 const struct built_in_command *x;
2810 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2811 if (strcmp(name, x->cmd) != 0)
2812 continue;
2813 debug_printf_exec("found builtin '%s'\n", name);
2814 return x;
2815 }
2816 return NULL;
2817}
2818
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002819#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002820static const struct function *find_function(const char *name)
2821{
2822 const struct function *funcp = G.top_func;
2823 while (funcp) {
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002824 if (strcmp(name, funcp->name) == 0) {
2825 break;
2826 }
2827 funcp = funcp->next;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002828 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002829 if (funcp)
2830 debug_printf_exec("found function '%s'\n", name);
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002831 return funcp;
2832}
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002833
Denis Vlasenkobc569742009-04-12 20:35:19 +00002834/* Note: takes ownership on name ptr */
2835static struct function *new_function(char *name)
2836{
2837 struct function *funcp;
2838 struct function **funcpp = &G.top_func;
2839
2840 while ((funcp = *funcpp) != NULL) {
2841 struct command *cmd;
2842
2843 if (strcmp(funcp->name, name) != 0) {
2844 funcpp = &funcp->next;
2845 continue;
2846 }
2847
2848 cmd = funcp->parent_cmd;
2849 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
2850 if (!cmd) {
2851 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
2852 free(funcp->name);
2853 /* Note: if !funcp->body, do not free body_as_string!
2854 * This is a special case of "-F name body" function:
2855 * body_as_string was not malloced! */
2856 if (funcp->body) {
2857 free_pipe_list(funcp->body);
2858#if !BB_MMU
2859 free(funcp->body_as_string);
2860#endif
2861 }
2862 } else {
2863 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
2864 cmd->argv[0] = funcp->name;
2865 cmd->group = funcp->body;
2866#if !BB_MMU
2867 cmd->group_as_string = funcp->body_as_string;
2868#endif
2869 }
2870 goto skip;
2871 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00002872 debug_printf_exec("remembering new function '%s'\n", name);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002873 funcp = *funcpp = xzalloc(sizeof(*funcp));
2874 /*funcp->next = NULL;*/
2875 skip:
2876 funcp->name = name;
2877 return funcp;
2878}
2879
Denis Vlasenko40e84372009-04-18 11:23:38 +00002880static void unset_func(const char *name)
2881{
2882 struct function *funcp;
2883 struct function **funcpp = &G.top_func;
2884
2885 while ((funcp = *funcpp) != NULL) {
2886 if (strcmp(funcp->name, name) == 0) {
2887 *funcpp = funcp->next;
2888 /* funcp is unlinked now, deleting it */
2889 free(funcp->name);
2890 /* Note: if !funcp->body, do not free body_as_string!
2891 * This is a special case of "-F name body" function:
2892 * body_as_string was not malloced! */
2893 if (funcp->body) {
2894 free_pipe_list(funcp->body);
2895#if !BB_MMU
2896 free(funcp->body_as_string);
2897#endif
2898 }
2899 free(funcp);
2900 break;
2901 }
Denis Vlasenko73010672009-04-18 11:25:18 +00002902 funcpp = &funcp->next;
Denis Vlasenko40e84372009-04-18 11:23:38 +00002903 }
2904}
2905
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002906#if BB_MMU
2907#define exec_function(nommu_save, funcp, argv) \
2908 exec_function(funcp, argv)
2909#endif
2910static void exec_function(nommu_save_t *nommu_save,
2911 const struct function *funcp,
2912 char **argv) NORETURN;
2913static void exec_function(nommu_save_t *nommu_save,
2914 const struct function *funcp,
2915 char **argv)
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002916{
2917# if BB_MMU
2918 int n = 1;
2919
2920 argv[0] = G.global_argv[0];
2921 G.global_argv = argv;
2922 while (*++argv)
2923 n++;
2924 G.global_argc = n;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002925 /* On MMU, funcp->body is always non-NULL */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00002926 n = run_list(funcp->body);
2927 fflush(NULL);
2928 _exit(n);
2929# else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00002930 re_execute_shell(&nommu_save->argv_from_re_execing,
2931 funcp->body_as_string,
2932 G.global_argv[0],
2933 argv + 1);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002934# endif
2935}
2936
2937static int run_function(const struct function *funcp, char **argv)
2938{
Denis Vlasenko270b1c32009-04-17 18:54:50 +00002939 int rc;
2940 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00002941#if ENABLE_HUSH_FUNCTIONS
2942 smallint sv_flg;
2943#endif
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002944
Denis Vlasenko270b1c32009-04-17 18:54:50 +00002945 save_and_replace_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00002946#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00002947 /* "we are in function, ok to use return" */
2948 sv_flg = G.flag_return_in_progress;
2949 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00002950#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00002951
Denis Vlasenkobc569742009-04-12 20:35:19 +00002952 /* On MMU, funcp->body is always non-NULL */
2953#if !BB_MMU
2954 if (!funcp->body) {
2955 /* Function defined by -F */
2956 parse_and_run_string(funcp->body_as_string);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00002957 rc = G.last_exitcode;
Denis Vlasenkobc569742009-04-12 20:35:19 +00002958 } else
2959#endif
2960 {
Denis Vlasenko270b1c32009-04-17 18:54:50 +00002961 rc = run_list(funcp->body);
Denis Vlasenkobc569742009-04-12 20:35:19 +00002962 }
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00002963
Mike Frysinger885b6f22009-04-18 21:04:25 +00002964#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00002965 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00002966#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00002967 restore_G_args(&sv, argv);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00002968
Denis Vlasenko270b1c32009-04-17 18:54:50 +00002969 return rc;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00002970}
2971#endif
2972
2973
Denis Vlasenkocc90f442009-04-08 16:40:34 +00002974#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002975#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2976 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2977#define pseudo_exec(nommu_save, command, argv_expanded) \
2978 pseudo_exec(command, argv_expanded)
2979#endif
2980
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002981/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00002982 * Never returns.
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00002983 * Don't exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00002984 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002985 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002986static void pseudo_exec_argv(nommu_save_t *nommu_save,
2987 char **argv, int assignment_cnt,
2988 char **argv_expanded) NORETURN;
2989static void pseudo_exec_argv(nommu_save_t *nommu_save,
2990 char **argv, int assignment_cnt,
2991 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00002992{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002993 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002994
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002995 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002996 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002997 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002998
Denis Vlasenko9504e442008-10-29 01:19:15 +00002999 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003000#if BB_MMU
3001 putenv_all(new_env);
3002 free(new_env); /* optional */
3003#else
3004 nommu_save->new_env = new_env;
3005 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003006#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003007 if (argv_expanded) {
3008 argv = argv_expanded;
3009 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00003010 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00003011#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003012 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003013#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003014 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00003015
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003016#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
3017 if (strchr(argv[0], '/') != NULL)
3018 goto skip;
3019#endif
3020
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003021 /* On NOMMU, we must never block!
3022 * Example: { sleep 99999 | read line } & echo Ok
3023 * read builtin will block on read syscall, leaving parent blocked
3024 * in vfork. Therefore we can't do this:
3025 */
3026#if BB_MMU
3027 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00003028 * Depending on context, this might be redundant. But it's
3029 * easier to waste a few CPU cycles than it is to figure out
3030 * if this is one of those cases.
3031 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003032 {
3033 int rcode;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003034 const struct built_in_command *x = find_builtin(argv[0]);
3035 if (x) {
3036 rcode = x->function(argv);
3037 fflush(NULL);
3038 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00003039 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003040 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003041#endif
3042#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003043 /* Check if the command matches any functions */
3044 {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003045 const struct function *funcp = find_function(argv[0]);
3046 if (funcp) {
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003047 exec_function(nommu_save, funcp, argv);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003048 }
3049 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003050#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00003051
Denis Vlasenko80d14be2007-04-10 23:03:30 +00003052#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003053 /* Check if the command matches any busybox applets */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003054 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003055 int a = find_applet_by_name(argv[0]);
3056 if (a >= 0) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003057# if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003058 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003059 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00003060 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003061 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003062# endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003063 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003064 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003065 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
3066 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003067 /* If they called chroot or otherwise made the binary no longer
3068 * executable, fall through */
3069 }
3070 }
Eric Andersenaac75e52001-04-30 18:18:45 +00003071#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003072
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003073#if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003074 skip:
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003075#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003076 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003077 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003078 execvp(argv[0], argv);
Denis Vlasenkof9d4fc32009-04-21 20:40:51 +00003079 bb_perror_msg("can't execute '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00003080 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003081}
3082
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003083/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00003084 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003085static void pseudo_exec(nommu_save_t *nommu_save,
3086 struct command *command,
3087 char **argv_expanded) NORETURN;
3088static void pseudo_exec(nommu_save_t *nommu_save,
3089 struct command *command,
3090 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00003091{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003092 if (command->argv) {
3093 pseudo_exec_argv(nommu_save, command->argv,
3094 command->assignment_cnt, argv_expanded);
3095 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003096
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003097 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00003098 /* Cases when we are here:
3099 * ( list )
3100 * { list } &
3101 * ... | ( list ) | ...
3102 * ... | { list } | ...
3103 */
3104#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00003105 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003106 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003107 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003108 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00003109 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003110 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00003111 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003112#else
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003113 re_execute_shell(&nommu_save->argv_from_re_execing,
3114 command->group_as_string,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003115 G.global_argv[0],
3116 G.global_argv + 1);
Denis Vlasenko8412d792007-10-01 09:59:47 +00003117#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003118 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003119
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003120 /* Case when we are here: ... | >file */
3121 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003122 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00003123}
3124
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003125#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003126static const char *get_cmdtext(struct pipe *pi)
3127{
3128 char **argv;
3129 char *p;
3130 int len;
3131
3132 /* This is subtle. ->cmdtext is created only on first backgrounding.
3133 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003134 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003135 if (pi->cmdtext)
3136 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003137 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003138 if (!argv || !argv[0]) {
3139 pi->cmdtext = xzalloc(1);
3140 return pi->cmdtext;
3141 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003142
3143 len = 0;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003144 do {
3145 len += strlen(*argv) + 1;
3146 } while (*++argv);
3147 p = xmalloc(len);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003148 pi->cmdtext = p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003149 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003150 do {
3151 len = strlen(*argv);
3152 memcpy(p, *argv, len);
3153 p += len;
3154 *p++ = ' ';
3155 } while (*++argv);
3156 p[-1] = '\0';
3157 return pi->cmdtext;
3158}
3159
Eric Andersenbafd94f2001-05-02 16:11:59 +00003160static void insert_bg_job(struct pipe *pi)
3161{
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003162 struct pipe *job, **jobp;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003163 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003164
3165 /* Linear search for the ID of the job to use */
3166 pi->jobid = 1;
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003167 for (job = G.job_list; job; job = job->next)
3168 if (job->jobid >= pi->jobid)
3169 pi->jobid = job->jobid + 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003170
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003171 /* Add job to the list of running jobs */
3172 jobp = &G.job_list;
3173 while ((job = *jobp) != NULL)
3174 jobp = &job->next;
3175 job = *jobp = xmalloc(sizeof(*job));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003176
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003177 *job = *pi; /* physical copy */
3178 job->next = NULL;
3179 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
3180 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003181 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003182 job->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003183 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003184 }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003185 job->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00003186
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003187 if (G_interactive_fd)
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003188 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
3189 /* Last command's pid goes to $! */
3190 G.last_bg_pid = job->cmds[job->num_cmds - 1].pid;
3191 G.last_jobid = job->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003192}
3193
Eric Andersenbafd94f2001-05-02 16:11:59 +00003194static void remove_bg_job(struct pipe *pi)
3195{
3196 struct pipe *prev_pipe;
3197
Denis Vlasenko87a86552008-07-29 19:43:10 +00003198 if (pi == G.job_list) {
3199 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003200 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003201 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003202 while (prev_pipe->next != pi)
3203 prev_pipe = prev_pipe->next;
3204 prev_pipe->next = pi->next;
3205 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00003206 if (G.job_list)
3207 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00003208 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00003209 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00003210}
Eric Andersen028b65b2001-06-28 01:10:11 +00003211
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003212/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00003213static void delete_finished_bg_job(struct pipe *pi)
3214{
3215 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003216 pi->stopped_cmds = 0;
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003217 free_pipe(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003218 free(pi);
3219}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003220#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003221
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003222/* Check to see if any processes have exited -- if they
3223 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00003224static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00003225{
Eric Andersenc798b072001-06-22 06:23:03 +00003226 int attributes;
3227 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003228#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00003229 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003230#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00003231 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003232 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003233
Denis Vlasenkod5762932009-03-31 11:22:57 +00003234 debug_printf_jobs("checkjobs %p\n", fg_pipe);
3235
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003236 errno = 0;
3237// if (G.handled_SIGCHLD == G.count_SIGCHLD)
3238// /* avoid doing syscall, nothing there anyway */
3239// return rcode;
3240
Eric Andersenc798b072001-06-22 06:23:03 +00003241 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003242 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00003243 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00003244
Denis Vlasenko1359da62007-04-21 23:27:30 +00003245/* Do we do this right?
3246 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003247 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00003248 * [3]+ Stopped sleep 20 | false
3249 * bash-3.00# echo $?
3250 * 1 <========== bg pipe is not fully done, but exitcode is already known!
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003251 * [hush 1.14.0: yes we do it right]
Denis Vlasenko1359da62007-04-21 23:27:30 +00003252 */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003253 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003254 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003255 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003256 int dead;
3257
3258// i = G.count_SIGCHLD;
3259 childpid = waitpid(-1, &status, attributes);
3260 if (childpid <= 0) {
3261 if (childpid && errno != ECHILD)
3262 bb_perror_msg("waitpid");
3263// else /* Until next SIGCHLD, waitpid's are useless */
3264// G.handled_SIGCHLD = i;
3265 break;
3266 }
3267 dead = WIFEXITED(status) || WIFSIGNALED(status);
3268
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00003269#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00003270 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003271 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003272 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3273 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003274 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003275 childpid, WTERMSIG(status), WEXITSTATUS(status));
3276 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00003277 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00003278 childpid, WEXITSTATUS(status));
3279#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003280 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00003281 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003282 for (i = 0; i < fg_pipe->num_cmds; i++) {
3283 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3284 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003285 continue;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003286 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003287 fg_pipe->cmds[i].pid = 0;
3288 fg_pipe->alive_cmds--;
3289 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003290 /* last process gives overall exitstatus */
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003291 /* Note: is WIFSIGNALED, WEXITSTATUS = sig + 128 */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003292 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003293 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko40e84372009-04-18 11:23:38 +00003294 /* bash prints killing signal's name for *last*
3295 * process in pipe (prints just newline for SIGINT).
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003296 * Mimic this. Example: "sleep 5" + ^\
Denis Vlasenko40e84372009-04-18 11:23:38 +00003297 */
3298 if (WIFSIGNALED(status)) {
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003299 int sig = WTERMSIG(status);
3300 printf("%s\n", sig == SIGINT ? "" : get_signame(sig));
Denis Vlasenko40e84372009-04-18 11:23:38 +00003301 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00003302 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003303 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003304 fg_pipe->cmds[i].is_stopped = 1;
3305 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00003306 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003307 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3308 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3309 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003310 /* All processes in fg pipe have exited or stopped */
3311/* Note: *non-interactive* bash does not continue if all processes in fg pipe
3312 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
3313 * and "killall -STOP cat" */
3314 if (G_interactive_fd) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003315#if ENABLE_HUSH_JOB
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003316 if (fg_pipe->alive_cmds)
3317 insert_bg_job(fg_pipe);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003318#endif
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003319 return rcode;
3320 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003321 }
3322 /* There are still running processes in the fg pipe */
3323 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00003324 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003325 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00003326 }
3327
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003328#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003329 /* We asked to wait for bg or orphaned children */
3330 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003331 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003332 for (i = 0; i < pi->num_cmds; i++) {
3333 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003334 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00003335 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00003336 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003337 /* Happens when shell is used as init process (init=/bin/sh) */
3338 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003339 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00003340
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003341 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00003342 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00003343 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003344 pi->cmds[i].pid = 0;
3345 pi->alive_cmds--;
3346 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003347 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00003348 printf(JOB_STATUS_FORMAT, pi->jobid,
3349 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00003350 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00003351 }
3352 } else {
3353 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003354 pi->cmds[i].is_stopped = 1;
3355 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00003356 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003357#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00003358 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00003359
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003360 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00003361}
3362
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003363#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00003364static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3365{
3366 pid_t p;
3367 int rcode = checkjobs(fg_pipe);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003368 if (G.saved_tty_pgrp) {
3369 /* Job finished, move the shell to the foreground */
3370 p = getpgrp(); /* our process group id */
3371 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
3372 tcsetpgrp(G_interactive_fd, p);
3373 }
Denis Vlasenko52881e92007-04-21 13:42:52 +00003374 return rcode;
3375}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003376#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00003377
Denis Vlasenko34d4d892009-04-04 20:24:37 +00003378/* Start all the jobs, but don't wait for anything to finish.
3379 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00003380 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00003381 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00003382 * to finish to determine the exit status of the pipe. If the pipe
3383 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00003384 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00003385 * return value.
3386 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00003387 * Returns -1 only if started some children. IOW: we have to
3388 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00003389 *
3390 * The only case when we do not need to [v]fork is when the pipe
3391 * is single, non-backgrounded, non-subshell command. Examples:
3392 * cmd ; ... { list } ; ...
3393 * cmd && ... { list } && ...
3394 * cmd || ... { list } || ...
3395 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3396 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00003397 * with run_list. If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00003398 *
3399 * Cases when we must fork:
3400 * non-single: cmd | cmd
3401 * backgrounded: cmd & { list } &
3402 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00003403 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003404static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003405{
Denis Vlasenko552433b2009-04-04 19:29:21 +00003406 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003407 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003408 int nextin;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003409 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003410 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003411 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003412 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003413 /* it is not always needed, but we aim to smaller code */
3414 int squirrel[] = { -1, -1, -1 };
3415 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003416
Denis Vlasenko552433b2009-04-04 19:29:21 +00003417 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003418 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003419
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003420 IF_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003421 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003422 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003423 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003424
Denis Vlasenko552433b2009-04-04 19:29:21 +00003425 if (pi->num_cmds != 1
3426 || pi->followup == PIPE_BG
3427 || command->grp_type == GRP_SUBSHELL
3428 ) {
3429 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003430 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003431
Denis Vlasenko552433b2009-04-04 19:29:21 +00003432 pi->alive_cmds = 1;
3433
3434 debug_printf_exec(": group:%p argv:'%s'\n",
3435 command->group, command->argv ? command->argv[0] : "NONE");
3436
3437 if (command->group) {
3438#if ENABLE_HUSH_FUNCTIONS
3439 if (command->grp_type == GRP_FUNCTION) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003440 /* "executing" func () { list } */
3441 struct function *funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003442
Denis Vlasenkobc569742009-04-12 20:35:19 +00003443 funcp = new_function(command->argv[0]);
3444 /* funcp->name is already set to argv[0] */
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003445 funcp->body = command->group;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003446#if !BB_MMU
3447 funcp->body_as_string = command->group_as_string;
3448 command->group_as_string = NULL;
3449#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003450 command->group = NULL;
3451 command->argv[0] = NULL;
Denis Vlasenkoed055212009-04-11 10:37:10 +00003452 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
3453 funcp->parent_cmd = command;
3454 command->child_func = funcp;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003455
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003456 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
3457 debug_leave();
Denis Vlasenko552433b2009-04-04 19:29:21 +00003458 return EXIT_SUCCESS;
3459 }
3460#endif
3461 /* { list } */
3462 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003463 rcode = 1; /* exitcode if redir failed */
3464 if (setup_redirects(command, squirrel) == 0) {
3465 debug_printf_exec(": run_list\n");
3466 rcode = run_list(command->group) & 0xff;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003467 }
Eric Andersen04407e52001-06-07 16:42:05 +00003468 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003469 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003470 debug_leave();
3471 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003472 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003473 }
3474
Denis Vlasenko552433b2009-04-04 19:29:21 +00003475 argv = command->argv ? command->argv : (char **) &null_ptr;
3476 {
3477 const struct built_in_command *x;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003478#if ENABLE_HUSH_FUNCTIONS
3479 const struct function *funcp;
3480#else
3481 enum { funcp = 0 };
3482#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003483 char **new_env = NULL;
3484 char **old_env = NULL;
3485
Denis Vlasenko552433b2009-04-04 19:29:21 +00003486 if (argv[command->assignment_cnt] == NULL) {
3487 /* Assignments, but no command */
3488 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003489 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003490 restore_redirects(squirrel);
3491 /* Set shell variables */
3492 while (*argv) {
3493 p = expand_string_to_string(*argv);
3494 debug_printf_exec("set shell var:'%s'->'%s'\n",
3495 *argv, p);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003496 set_local_var(p, 0, 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003497 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003498 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003499 /* Do we need to flag set_local_var() errors?
3500 * "assignment to readonly var" and "putenv error"
3501 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003502 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003503 debug_leave();
3504 debug_printf_exec("run_pipe: return %d\n", rcode);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003505 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003506 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003507
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003508 /* Expand the rest into (possibly) many strings each */
Denis Vlasenko552433b2009-04-04 19:29:21 +00003509 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003510
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003511 x = find_builtin(argv_expanded[0]);
3512#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00003513 funcp = NULL;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003514 if (!x)
3515 funcp = find_function(argv_expanded[0]);
3516#endif
3517 if (x || funcp) {
3518 if (!funcp) {
3519 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3520 debug_printf("exec with redirects only\n");
3521 rcode = setup_redirects(command, NULL);
3522 goto clean_up_and_ret1;
3523 }
Eric Andersen25f27032001-04-26 23:22:31 +00003524 }
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003525 /* setup_redirects acts on file descriptors, not FILEs.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003526 * This is perfect for work that comes after exec().
3527 * Is it really safe for inline use? Experimentally,
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00003528 * things seem to work. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003529 rcode = setup_redirects(command, squirrel);
3530 if (rcode == 0) {
3531 new_env = expand_assignments(argv, command->assignment_cnt);
3532 old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003533 if (!funcp) {
3534 debug_printf_exec(": builtin '%s' '%s'...\n",
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003535 x->cmd, argv_expanded[1]);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003536 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00003537 fflush(NULL);
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003538 }
3539#if ENABLE_HUSH_FUNCTIONS
3540 else {
3541 debug_printf_exec(": function '%s' '%s'...\n",
3542 funcp->name, argv_expanded[1]);
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00003543 rcode = run_function(funcp, argv_expanded) & 0xff;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003544 }
3545#endif
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003546 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003547#if ENABLE_FEATURE_SH_STANDALONE
3548 clean_up_and_ret:
3549#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003550 restore_redirects(squirrel);
3551 free_strings_and_unsetenv(new_env, 1);
3552 putenv_all(old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003553 /* Free the pointers, but the strings themselves
3554 * are in environ now, don't use free_strings! */
3555 free(old_env);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003556 clean_up_and_ret1:
3557 free(argv_expanded);
3558 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003559 debug_leave();
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003560 debug_printf_exec("run_pipe return %d\n", rcode);
3561 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003562 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00003563
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003564#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003565 i = find_applet_by_name(argv_expanded[0]);
3566 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003567 rcode = setup_redirects(command, squirrel);
3568 if (rcode == 0) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003569 new_env = expand_assignments(argv, command->assignment_cnt);
3570 old_env = putenv_all_and_save_old(new_env);
3571 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003572 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003573 rcode = run_nofork_applet(i, argv_expanded);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003574 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003575 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003576 }
3577#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003578 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003579 }
3580
Denis Vlasenko552433b2009-04-04 19:29:21 +00003581 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003582 /* NB: argv_expanded may already be created, and that
3583 * might include `cmd` runs! Do not rerun it! We *must*
3584 * use argv_expanded if it's non-NULL */
3585
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003586 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003587 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003588 nextin = 0;
3589
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003590 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003591 struct fd_pair pipefds;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003592#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003593 volatile nommu_save_t nommu_save;
3594 nommu_save.new_env = NULL;
3595 nommu_save.old_env = NULL;
3596 nommu_save.argv = NULL;
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003597 nommu_save.argv_from_re_execing = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003598#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003599 command = &(pi->cmds[i]);
3600 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003601 debug_printf_exec(": pipe member '%s' '%s'...\n",
3602 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003603 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003604 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003605 }
Eric Andersen25f27032001-04-26 23:22:31 +00003606
3607 /* pipes are inserted between pairs of commands */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003608 pipefds.rd = 0;
3609 pipefds.wr = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003610 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003611 xpiped_pair(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003612
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003613 command->pid = BB_MMU ? fork() : vfork();
3614 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003615#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003616 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003617
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003618 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003619 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003620 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003621 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003622 pgrp = pi->pgrp;
3623 if (pgrp < 0) /* true for 1st process only */
3624 pgrp = getpid();
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00003625 if (setpgid(0, pgrp) == 0
3626 && pi->followup != PIPE_BG
3627 && G.saved_tty_pgrp /* we have ctty */
3628 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003629 /* We do it in *every* child, not just first,
3630 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003631 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003632 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003633 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003634#endif
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003635 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
3636 /* 1st cmd in backgrounded pipe
3637 * should have its stdin /dev/null'ed */
3638 close(0);
3639 if (open(bb_dev_null, O_RDONLY))
3640 xopen("/", O_RDONLY);
3641 } else {
3642 xmove_fd(nextin, 0);
3643 }
3644 xmove_fd(pipefds.wr, 1);
3645 if (pipefds.rd > 1)
3646 close(pipefds.rd);
Eric Andersen25f27032001-04-26 23:22:31 +00003647 /* Like bash, explicit redirects override pipes,
3648 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003649 if (setup_redirects(command, NULL))
3650 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00003651
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003652 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003653 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3654
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003655 /* Stores to nommu_save list of env vars putenv'ed
3656 * (NOMMU, on MMU we don't need that) */
3657 /* cast away volatility... */
3658 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003659 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00003660 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003661
Denis Vlasenkof9375282009-04-05 19:13:39 +00003662 /* parent or error */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003663 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003664#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003665 /* Clean up after vforked child */
3666 free(nommu_save.argv);
Denis Vlasenko27014ed2009-04-15 21:48:23 +00003667 free(nommu_save.argv_from_re_execing);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003668 free_strings_and_unsetenv(nommu_save.new_env, 1);
3669 putenv_all(nommu_save.old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003670 /* Free the pointers, but the strings themselves
3671 * are in environ now, don't use free_strings! */
3672 free(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003673#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003674 free(argv_expanded);
3675 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003676 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003677 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003678 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003679 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003680 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003681#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003682 /* Second and next children need to know pid of first one */
3683 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003684 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003685#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003686 }
Eric Andersen25f27032001-04-26 23:22:31 +00003687
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003688 if (i)
3689 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003690 if ((i + 1) < pi->num_cmds)
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003691 close(pipefds.wr);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003692 /* Pass read (output) pipe end to next iteration */
Denis Vlasenko8c64e032009-04-20 00:34:01 +00003693 nextin = pipefds.rd;
Eric Andersen25f27032001-04-26 23:22:31 +00003694 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003695
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003696 if (!pi->alive_cmds) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003697 debug_leave();
Denis Vlasenko05743d72008-02-10 12:10:08 +00003698 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3699 return 1;
3700 }
3701
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003702 debug_leave();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003703 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003704 return -1;
3705}
3706
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003707#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003708static void debug_print_tree(struct pipe *pi, int lvl)
3709{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003710 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003711 [PIPE_SEQ] = "SEQ",
3712 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003713 [PIPE_OR ] = "OR" ,
3714 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003715 };
3716 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003717 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003718#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003719 [RES_IF ] = "IF" ,
3720 [RES_THEN ] = "THEN" ,
3721 [RES_ELIF ] = "ELIF" ,
3722 [RES_ELSE ] = "ELSE" ,
3723 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003724#endif
3725#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003726 [RES_FOR ] = "FOR" ,
3727 [RES_WHILE] = "WHILE",
3728 [RES_UNTIL] = "UNTIL",
3729 [RES_DO ] = "DO" ,
3730 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003731#endif
3732#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003733 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003734#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003735#if ENABLE_HUSH_CASE
3736 [RES_CASE ] = "CASE" ,
3737 [RES_MATCH] = "MATCH",
3738 [RES_CASEI] = "CASEI",
3739 [RES_ESAC ] = "ESAC" ,
3740#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00003741 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003742 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003743 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003744 static const char *const GRPTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003745 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00003746 "()",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003747#if ENABLE_HUSH_FUNCTIONS
3748 "func()",
3749#endif
3750 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003751
3752 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003753
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003754 pin = 0;
3755 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003756 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3757 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003758 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003759 while (prn < pi->num_cmds) {
3760 struct command *command = &pi->cmds[prn];
3761 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003762
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003763 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003764 lvl*2, "", prn,
3765 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003766 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003767 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003768 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003769 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003770 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003771 prn++;
3772 continue;
3773 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003774 if (argv) while (*argv) {
3775 fprintf(stderr, " '%s'", *argv);
3776 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003777 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003778 fprintf(stderr, "\n");
3779 prn++;
3780 }
3781 pi = pi->next;
3782 pin++;
3783 }
3784}
3785#endif
3786
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003787/* NB: called by pseudo_exec, and therefore must not modify any
3788 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003789static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003790{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003791#if ENABLE_HUSH_CASE
3792 char *case_word = NULL;
3793#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003794#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003795 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003796 char *for_varname = NULL;
3797 char **for_lcur = NULL;
3798 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00003799#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003800 smallint last_followup;
3801 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003802#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003803 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003804#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003805 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003806#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00003807#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003808 smallint rword; /* enum reserved_style */
3809 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003810#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003811
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003812 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003813 debug_enter();
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003814
Denis Vlasenko06810332007-05-21 23:30:54 +00003815#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003816 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003817 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3818 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003819 continue;
3820 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003821 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003822 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003823 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003824 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003825 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003826 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003827 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003828 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003829 continue;
3830 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003831 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3832 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003833 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003834 syntax_error("malformed for");
Denis Vlasenko0701dca2009-04-11 10:38:47 +00003835 debug_leave();
Denis Vlasenko87a86552008-07-29 19:43:10 +00003836 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003837 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003838 }
3839 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003840#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003841
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003842 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00003843 * in order to return, no direct "return" statements please.
3844 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003845
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003846#if ENABLE_HUSH_JOB
Denis Vlasenkoc4ada792009-04-15 23:29:00 +00003847 G.run_list_level++;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003848#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003849
Denis Vlasenko0e151382009-04-06 18:40:31 +00003850#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003851 rword = RES_NONE;
3852 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003853#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003854 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003855 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003856
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003857 /* Go through list of pipes, (maybe) executing them. */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00003858 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00003859 if (G.flag_SIGINT)
3860 break;
3861
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003862 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003863 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3864 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00003865#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00003866 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003867 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00003868 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003869 /* start of a loop: remember where loop starts */
3870 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003871 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003872 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003873#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003874 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003875 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003876 if ((rcode == 0 && last_followup == PIPE_OR)
3877 || (rcode != 0 && last_followup == PIPE_AND)
3878 ) {
3879 /* It is "<true> || CMD" or "<false> && CMD"
3880 * and we should not execute CMD */
3881 debug_printf_exec("skipped cmd because of || or &&\n");
3882 last_followup = pi->followup;
3883 continue;
3884 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003885 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003886 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003887 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00003888#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003889 if (cond_code) {
3890 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00003891 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003892 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003893 /* "if <false> THEN cmd": skip cmd */
3894 continue;
3895 }
3896 } else {
3897 if (rword == RES_ELSE || rword == RES_ELIF) {
3898 /* "if <true> then ... ELSE/ELIF cmd":
3899 * skip cmd and all following ones */
3900 break;
3901 }
3902 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003903#endif
3904#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003905 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003906 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003907 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003908
3909 static const char encoded_dollar_at[] ALIGN1 = {
3910 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3911 }; /* encoded representation of "$@" */
3912 static const char *const encoded_dollar_at_argv[] = {
3913 encoded_dollar_at, NULL
3914 }; /* argv list with one element: "$@" */
3915 char **vals;
3916
3917 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003918 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003919 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003920 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003921 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003922 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003923 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003924 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003925 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003926 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003927 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003928 debug_print_strings("for_list made from", vals);
3929 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003930 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003931 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003932 for_varname = pi->cmds[0].argv[0];
3933 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003934 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003935 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003936 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00003937 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003938 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003939 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003940 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003941 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003942 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003943 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003944 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003945 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003946 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3947 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003948 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003949 if (rword == RES_IN) {
3950 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3951 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003952 if (rword == RES_DONE) {
3953 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003954 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003955#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003956#if ENABLE_HUSH_CASE
3957 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003958 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003959 continue;
3960 }
3961 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003962 char **argv;
3963
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003964 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3965 break;
3966 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003967 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003968 while (*argv) {
3969 char *pattern = expand_string_to_string(*argv);
3970 /* TODO: which FNM_xxx flags to use? */
3971 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3972 free(pattern);
3973 if (cond_code == 0) { /* match! we will execute this branch */
3974 free(case_word); /* make future "word)" stop */
3975 case_word = NULL;
3976 break;
3977 }
3978 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003979 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003980 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003981 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003982 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003983 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003984 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003985 }
3986#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003987 /* Just pressing <enter> in shell should check for jobs.
3988 * OTOH, in non-interactive shell this is useless
3989 * and only leads to extra job checks */
3990 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003991 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00003992 goto check_jobs_and_continue;
3993 continue;
3994 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003995
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003996 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00003997 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003998 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003999 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004000 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004001 {
4002 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004003#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00004004 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004005#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004006 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
4007 if (r != -1) {
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004008 /* We ran a builtin, function, or group.
4009 * rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004010 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004011 G.last_exitcode = rcode;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004012 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004013 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004014#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004015 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004016 if (G.flag_break_continue) {
4017 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004018 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004019 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004020 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004021 G.depth_break_continue--;
4022 if (G.depth_break_continue == 0)
4023 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004024 /* else: e.g. "continue 2" should *break* once, *then* continue */
4025 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004026 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004027 goto check_jobs_and_break;
4028 /* "continue": simulate end of loop */
4029 rword = RES_DONE;
4030 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004031 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004032#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00004033#if ENABLE_HUSH_FUNCTIONS
4034 if (G.flag_return_in_progress == 1)
4035 goto check_jobs_and_break;
4036#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004037 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004038 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004039 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004040 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
4041 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004042 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004043#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00004044 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004045 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004046#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004047 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004048 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004049 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004050#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004051 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004052 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004053 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004054 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004055 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004056 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004057#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004058 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004059 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004060 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00004061 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004062 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004063 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00004064 }
4065 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004066
4067 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00004068#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00004069 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004070 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00004071#endif
4072#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004073 /* Beware of "while false; true; do ..."! */
4074 if (pi->next && pi->next->res_word == RES_DO) {
4075 if (rword == RES_WHILE) {
4076 if (rcode) {
4077 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004078 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004079 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
4080 goto check_jobs_and_break;
4081 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00004082 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004083 if (rword == RES_UNTIL) {
4084 if (!rcode) {
4085 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004086 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004087 checkjobs(NULL);
4088 break;
4089 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004090 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00004091 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004092#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00004093
4094 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00004095 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004096 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004097
4098#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00004099 G.run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00004100#endif
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004101#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004102 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004103 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00004104 free(for_list);
4105#endif
4106#if ENABLE_HUSH_CASE
4107 free(case_word);
4108#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004109 debug_leave();
4110 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004111 return rcode;
4112}
4113
Eric Andersen25f27032001-04-26 23:22:31 +00004114/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004115static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00004116{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004117 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00004118 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00004119 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00004120 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004121 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004122 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004123 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00004124 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00004125 * but doing that now would hobble the debugging effort. */
Denis Vlasenko0701dca2009-04-11 10:38:47 +00004126 free_pipe_list(pi);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004127 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00004128 return rcode;
4129}
4130
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004131
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00004132static struct pipe *new_pipe(void)
4133{
Eric Andersen25f27032001-04-26 23:22:31 +00004134 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00004135 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004136 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004137 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00004138 return pi;
4139}
4140
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004141/* Command (member of a pipe) is complete, or we start a new pipe
4142 * if ctx->command is NULL.
4143 * No errors possible here.
4144 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004145static int done_command(struct parse_context *ctx)
4146{
4147 /* The command is really already in the pipe structure, so
4148 * advance the pipe counter and make a new, null command. */
4149 struct pipe *pi = ctx->pipe;
4150 struct command *command = ctx->command;
4151
4152 if (command) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004153 if (IS_NULL_CMD(command)) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004154 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004155 goto clear_and_ret;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004156 }
4157 pi->num_cmds++;
4158 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004159 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004160 } else {
4161 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
4162 }
4163
4164 /* Only real trickiness here is that the uncommitted
4165 * command structure is not counted in pi->num_cmds. */
4166 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004167 ctx->command = command = &pi->cmds[pi->num_cmds];
4168 clear_and_ret:
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004169 memset(command, 0, sizeof(*command));
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004170 return pi->num_cmds; /* used only for 0/nonzero check */
4171}
4172
4173static void done_pipe(struct parse_context *ctx, pipe_style type)
4174{
4175 int not_null;
4176
4177 debug_printf_parse("done_pipe entered, followup %d\n", type);
4178 /* Close previous command */
4179 not_null = done_command(ctx);
4180 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004181#if HAS_KEYWORDS
4182 ctx->pipe->pi_inverted = ctx->ctx_inverted;
4183 ctx->ctx_inverted = 0;
4184 ctx->pipe->res_word = ctx->ctx_res_w;
4185#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004186
4187 /* Without this check, even just <enter> on command line generates
4188 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004189 * IOW: it is safe to do it unconditionally. */
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004190 if (not_null
Denis Vlasenko7f959372009-04-14 08:06:59 +00004191#if ENABLE_HUSH_IF
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004192 || ctx->ctx_res_w == RES_FI
Denis Vlasenko7f959372009-04-14 08:06:59 +00004193#endif
4194#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004195 || ctx->ctx_res_w == RES_DONE
4196 || ctx->ctx_res_w == RES_FOR
4197 || ctx->ctx_res_w == RES_IN
Denis Vlasenko7f959372009-04-14 08:06:59 +00004198#endif
4199#if ENABLE_HUSH_CASE
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004200 || ctx->ctx_res_w == RES_ESAC
4201#endif
4202 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004203 struct pipe *new_p;
4204 debug_printf_parse("done_pipe: adding new pipe: "
4205 "not_null:%d ctx->ctx_res_w:%d\n",
4206 not_null, ctx->ctx_res_w);
4207 new_p = new_pipe();
4208 ctx->pipe->next = new_p;
4209 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004210 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004211 * they remain set for pipes inside if/while.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004212 * This is used to control execution.
4213 * RES_FOR and RES_IN are NOT sticky (needed to support
4214 * cases where variable or value happens to match a keyword):
4215 */
4216#if ENABLE_HUSH_LOOPS
4217 if (ctx->ctx_res_w == RES_FOR
4218 || ctx->ctx_res_w == RES_IN)
4219 ctx->ctx_res_w = RES_NONE;
4220#endif
4221#if ENABLE_HUSH_CASE
4222 if (ctx->ctx_res_w == RES_MATCH)
4223 ctx->ctx_res_w = RES_CASEI;
4224#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004225 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004226 /* Create the memory for command, roughly:
4227 * ctx->pipe->cmds = new struct command;
4228 * ctx->command = &ctx->pipe->cmds[0];
4229 */
4230 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00004231 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004232 }
4233 debug_printf_parse("done_pipe return\n");
4234}
4235
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004236static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004237{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004238 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00004239 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004240 /* Create the memory for command, roughly:
4241 * ctx->pipe->cmds = new struct command;
4242 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004243 */
4244 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004245}
4246
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004247/* If a reserved word is found and processed, parse context is modified
4248 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00004249 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004250#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004251struct reserved_combo {
4252 char literal[6];
4253 unsigned char res;
4254 unsigned char assignment_flag;
4255 int flag;
4256};
4257enum {
4258 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004259#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004260 FLAG_IF = (1 << RES_IF ),
4261 FLAG_THEN = (1 << RES_THEN ),
4262 FLAG_ELIF = (1 << RES_ELIF ),
4263 FLAG_ELSE = (1 << RES_ELSE ),
4264 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004265#endif
4266#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004267 FLAG_FOR = (1 << RES_FOR ),
4268 FLAG_WHILE = (1 << RES_WHILE),
4269 FLAG_UNTIL = (1 << RES_UNTIL),
4270 FLAG_DO = (1 << RES_DO ),
4271 FLAG_DONE = (1 << RES_DONE ),
4272 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004273#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004274#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004275 FLAG_MATCH = (1 << RES_MATCH),
4276 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004277#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004278 FLAG_START = (1 << RES_XXXX ),
4279};
4280
4281static const struct reserved_combo* match_reserved_word(o_string *word)
4282{
Eric Andersen25f27032001-04-26 23:22:31 +00004283 /* Mostly a list of accepted follow-up reserved words.
4284 * FLAG_END means we are done with the sequence, and are ready
4285 * to turn the compound list into a command.
4286 * FLAG_START means the word must start a new compound list.
4287 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004288 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00004289#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004290 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4291 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4292 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4293 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4294 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4295 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004296#endif
4297#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004298 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4299 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4300 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4301 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4302 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4303 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004304#endif
4305#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004306 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4307 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00004308#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004309 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004310 const struct reserved_combo *r;
4311
4312 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4313 if (strcmp(word->data, r->literal) == 0)
4314 return r;
4315 }
4316 return NULL;
4317}
Denis Vlasenkobb929512009-04-16 10:59:40 +00004318/* Return 0: not a keyword, 1: keyword
4319 */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004320static int reserved_word(o_string *word, struct parse_context *ctx)
4321{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004322#if ENABLE_HUSH_CASE
4323 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004324 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004325 };
4326#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004327 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00004328
Denis Vlasenkobb929512009-04-16 10:59:40 +00004329 if (word->o_quoted)
4330 return 0;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004331 r = match_reserved_word(word);
4332 if (!r)
4333 return 0;
4334
4335 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004336#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004337 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
4338 /* "case word IN ..." - IN part starts first match part */
4339 r = &reserved_match;
4340 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004341#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004342 if (r->flag == 0) { /* '!' */
4343 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004344 syntax_error("! ! command");
Denis Vlasenkobb929512009-04-16 10:59:40 +00004345 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00004346 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004347 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004348 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004349 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004350 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004351 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004352
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004353 old = xmalloc(sizeof(*old));
4354 debug_printf_parse("push stack %p\n", old);
4355 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004356 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004357 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004358 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004359 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004360 ctx->ctx_res_w = RES_SNTX;
4361 return 1;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004362 } else {
4363 /* "{...} fi" is ok. "{...} if" is not
4364 * Example:
4365 * if { echo foo; } then { echo bar; } fi */
4366 if (ctx->command->group)
4367 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004368 }
Denis Vlasenkobb929512009-04-16 10:59:40 +00004369
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004370 ctx->ctx_res_w = r->res;
4371 ctx->old_flag = r->flag;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004372 word->o_assignment = r->assignment_flag;
4373
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004374 if (ctx->old_flag & FLAG_END) {
4375 struct parse_context *old;
Denis Vlasenkobb929512009-04-16 10:59:40 +00004376
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004377 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004378 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004379 old = ctx->stack;
4380 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004381 old->command->grp_type = GRP_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004382#if !BB_MMU
4383 o_addstr(&old->as_string, ctx->as_string.data);
4384 o_free_unsafe(&ctx->as_string);
4385 old->command->group_as_string = xstrdup(old->as_string.data);
4386 debug_printf_parse("pop, remembering as:'%s'\n",
4387 old->command->group_as_string);
4388#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004389 *ctx = *old; /* physical copy */
4390 free(old);
4391 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004392 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004393}
Denis Vlasenko06810332007-05-21 23:30:54 +00004394#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004395
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004396/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004397 * Normal return is 0. Syntax errors return 1.
4398 * Note: on return, word is reset, but not o_free'd!
4399 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004400static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00004401{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004402 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00004403
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004404 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004405 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004406 debug_printf_parse("done_word return 0: true null, ignored\n");
4407 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004408 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004409
Eric Andersen25f27032001-04-26 23:22:31 +00004410 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004411 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4412 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004413 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4414 * "2.7 Redirection
4415 * ...the word that follows the redirection operator
4416 * shall be subjected to tilde expansion, parameter expansion,
4417 * command substitution, arithmetic expansion, and quote
4418 * removal. Pathname expansion shall not be performed
4419 * on the word by a non-interactive shell; an interactive
4420 * shell may perform it, but shall do so only when
4421 * the expansion would result in one word."
4422 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004423 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004424 /* Cater for >\file case:
4425 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4426 * Same with heredocs:
4427 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4428 */
4429 unbackslash(ctx->pending_redirect->rd_filename);
4430 /* Is it <<"HEREDOC"? */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004431 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4432 && word->o_quoted
4433 ) {
4434 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4435 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004436 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004437 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00004438 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004439 /* If this word wasn't an assignment, next ones definitely
4440 * can't be assignments. Even if they look like ones. */
4441 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4442 && word->o_assignment != WORD_IS_KEYWORD
4443 ) {
4444 word->o_assignment = NOT_ASSIGNMENT;
4445 } else {
4446 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4447 command->assignment_cnt++;
4448 word->o_assignment = MAYBE_ASSIGNMENT;
4449 }
4450
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004451#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004452# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004453 if (ctx->ctx_dsemicolon
4454 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4455 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004456 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004457 /* ctx->ctx_res_w = RES_MATCH; */
4458 ctx->ctx_dsemicolon = 0;
4459 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004460# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004461 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004462# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004463 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4464 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004465# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004466 ) {
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004467 debug_printf_parse("checking '%s' for reserved-ness\n", word->data);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004468 if (reserved_word(word, ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004469 o_reset_to_empty_unquoted(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004470 debug_printf_parse("done_word return %d\n",
4471 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004472 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004473 }
Eric Andersen25f27032001-04-26 23:22:31 +00004474 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004475#endif
Denis Vlasenkobb929512009-04-16 10:59:40 +00004476 if (command->group) {
4477 /* "{ echo foo; } echo bar" - bad */
4478 syntax_error_at(word->data);
4479 debug_printf_parse("done_word return 1: syntax error, "
4480 "groups and arglists don't mix\n");
4481 return 1;
4482 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004483 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004484 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4485 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004486 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004487 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004488 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004489 char *p = word->data;
4490 while (p[0] == SPECIAL_VAR_SYMBOL
4491 && (p[1] & 0x7f) == '@'
4492 && p[2] == SPECIAL_VAR_SYMBOL
4493 ) {
4494 p += 3;
4495 }
4496 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004497 /* saw no "$@", or not only "$@" but some
4498 * real text is there too */
4499 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004500 * e.g. "", $empty"" etc to not disappear */
4501 o_addchr(word, SPECIAL_VAR_SYMBOL);
4502 o_addchr(word, SPECIAL_VAR_SYMBOL);
4503 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004504 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004505 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004506 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004507 }
Eric Andersen25f27032001-04-26 23:22:31 +00004508
Denis Vlasenko06810332007-05-21 23:30:54 +00004509#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004510 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004511 if (word->o_quoted
4512 || !is_well_formed_var_name(command->argv[0], '\0')
4513 ) {
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004514 /* bash says just "not a valid identifier" */
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004515 syntax_error("not a valid identifier in for");
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004516 return 1;
4517 }
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004518 /* Force FOR to have just one word (variable name) */
4519 /* NB: basically, this makes hush see "for v in ..."
4520 * syntax as if it is "for v; in ...". FOR and IN become
4521 * two pipe structs in parse tree. */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004522 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004523 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004524#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004525#if ENABLE_HUSH_CASE
4526 /* Force CASE to have just one word */
4527 if (ctx->ctx_res_w == RES_CASE) {
4528 done_pipe(ctx, PIPE_SEQ);
4529 }
4530#endif
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004531
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004532 o_reset_to_empty_unquoted(word);
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00004533
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004534 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004535 return 0;
4536}
4537
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004538
4539/* Peek ahead in the input to find out if we have a "&n" construct,
4540 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004541 * Return:
4542 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4543 * REDIRFD_SYNTAX_ERR if syntax error,
4544 * REDIRFD_TO_FILE if no & was seen,
4545 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004546 */
4547#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004548#define parse_redir_right_fd(as_string, input) \
4549 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004550#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004551static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004552{
4553 int ch, d, ok;
4554
4555 ch = i_peek(input);
4556 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004557 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004558
4559 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004560 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004561 ch = i_peek(input);
4562 if (ch == '-') {
4563 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004564 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004565 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004566 }
4567 d = 0;
4568 ok = 0;
4569 while (ch != EOF && isdigit(ch)) {
4570 d = d*10 + (ch-'0');
4571 ok = 1;
4572 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004573 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004574 ch = i_peek(input);
4575 }
4576 if (ok) return d;
4577
4578//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4579
4580 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004581 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004582}
4583
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004584/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004585 */
4586static int parse_redirect(struct parse_context *ctx,
4587 int fd,
4588 redir_type style,
4589 struct in_str *input)
4590{
4591 struct command *command = ctx->command;
4592 struct redir_struct *redir;
4593 struct redir_struct **redirp;
4594 int dup_num;
4595
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004596 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004597 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004598 /* Check for a '>&1' type redirect */
4599 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4600 if (dup_num == REDIRFD_SYNTAX_ERR)
4601 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004602 } else {
4603 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004604 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004605 if (dup_num) { /* <<-... */
4606 ch = i_getch(input);
4607 nommu_addchr(&ctx->as_string, ch);
4608 ch = i_peek(input);
4609 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004610 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004611
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004612 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004613 int ch = i_peek(input);
4614 if (ch == '|') {
4615 /* >|FILE redirect ("clobbering" >).
4616 * Since we do not support "set -o noclobber" yet,
4617 * >| and > are the same for now. Just eat |.
4618 */
4619 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004620 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004621 }
4622 }
4623
4624 /* Create a new redir_struct and append it to the linked list */
4625 redirp = &command->redirects;
4626 while ((redir = *redirp) != NULL) {
4627 redirp = &(redir->next);
4628 }
4629 *redirp = redir = xzalloc(sizeof(*redir));
4630 /* redir->next = NULL; */
4631 /* redir->rd_filename = NULL; */
4632 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004633 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004634
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004635 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4636 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004637
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004638 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004639 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004640 /* Erik had a check here that the file descriptor in question
4641 * is legit; I postpone that to "run time"
4642 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004643 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4644 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004645 } else {
4646 /* Set ctx->pending_redirect, so we know what to do at the
4647 * end of the next parsed word. */
4648 ctx->pending_redirect = redir;
4649 }
4650 return 0;
4651}
4652
Eric Andersen25f27032001-04-26 23:22:31 +00004653/* If a redirect is immediately preceded by a number, that number is
4654 * supposed to tell which file descriptor to redirect. This routine
4655 * looks for such preceding numbers. In an ideal world this routine
4656 * needs to handle all the following classes of redirects...
4657 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4658 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4659 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4660 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004661 *
4662 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4663 * "2.7 Redirection
4664 * ... If n is quoted, the number shall not be recognized as part of
4665 * the redirection expression. For example:
4666 * echo \2>a
4667 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004668 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004669 *
4670 * A -1 return means no valid number was found,
4671 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004672 */
4673static int redirect_opt_num(o_string *o)
4674{
4675 int num;
4676
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004677 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004678 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004679 num = bb_strtou(o->data, NULL, 10);
4680 if (errno || num < 0)
4681 return -1;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004682 o_reset_to_empty_unquoted(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004683 return num;
4684}
4685
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004686#if BB_MMU
4687#define fetch_till_str(as_string, input, word, skip_tabs) \
4688 fetch_till_str(input, word, skip_tabs)
4689#endif
4690static char *fetch_till_str(o_string *as_string,
4691 struct in_str *input,
4692 const char *word,
4693 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004694{
4695 o_string heredoc = NULL_O_STRING;
4696 int past_EOL = 0;
4697 int ch;
4698
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004699 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004700 while (1) {
4701 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004702 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004703 if (ch == '\n') {
4704 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4705 heredoc.data[past_EOL] = '\0';
4706 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4707 return heredoc.data;
4708 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004709 do {
4710 o_addchr(&heredoc, ch);
4711 past_EOL = heredoc.length;
4712 jump_in:
4713 do {
4714 ch = i_getch(input);
4715 nommu_addchr(as_string, ch);
4716 } while (skip_tabs && ch == '\t');
4717 } while (ch == '\n');
4718 }
4719 if (ch == EOF) {
4720 o_free_unsafe(&heredoc);
4721 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004722 }
4723 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004724 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004725 }
4726}
4727
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004728/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4729 * and load them all. There should be exactly heredoc_cnt of them.
4730 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004731static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4732{
4733 struct pipe *pi = ctx->list_head;
4734
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004735 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004736 int i;
4737 struct command *cmd = pi->cmds;
4738
4739 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4740 pi->num_cmds,
4741 cmd->argv ? cmd->argv[0] : "NONE");
4742 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004743 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004744
4745 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4746 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004747 while (redir) {
4748 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004749 char *p;
4750
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004751 redir->rd_type = REDIRECT_HEREDOC2;
4752 /* redir->dup is (ab)used to indicate <<- */
4753 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004754 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004755 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004756 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004757 return 1;
4758 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004759 free(redir->rd_filename);
4760 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004761 heredoc_cnt--;
4762 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004763 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004764 }
4765 cmd++;
4766 }
4767 pi = pi->next;
4768 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004769#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004770 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004771 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004772 bb_error_msg_and_die("heredoc BUG 2");
4773#endif
4774 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004775}
4776
4777
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004778#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004779static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004780{
4781 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004782 int pid, channel[2];
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004783#if !BB_MMU
4784 char **to_free;
4785#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004786
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00004787 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00004788 pid = BB_MMU ? fork() : vfork();
4789 if (pid < 0)
4790 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004791
Denis Vlasenko05743d72008-02-10 12:10:08 +00004792 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004793 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004794 /* Process substitution is not considered to be usual
4795 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004796 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4797 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00004798 bb_signals(0
4799 + (1 << SIGTSTP)
4800 + (1 << SIGTTIN)
4801 + (1 << SIGTTOU)
4802 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004803 close(channel[0]); /* NB: close _first_, then move fd! */
4804 xmove_fd(channel[1], 1);
4805 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004806 IF_HUSH_JOB(G.run_list_level = 1;)
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004807#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004808 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004809 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004810 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004811#else
4812 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00004813 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4814 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004815 * echo OK
4816 */
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004817 re_execute_shell(&to_free,
4818 s,
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004819 G.global_argv[0],
4820 G.global_argv + 1);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004821#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004822 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004823
4824 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004825 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko27014ed2009-04-15 21:48:23 +00004826#if !BB_MMU
4827 free(to_free);
4828#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004829 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004830 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00004831 return pf;
4832}
4833
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004834/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004835static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004836{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004837 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004838 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004839 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004840
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004841 pf = generate_stream_from_string(s);
4842 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00004843 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004844 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00004845
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004846 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004847 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004848 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004849 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004850 if (ch == '\n') {
4851 eol_cnt++;
4852 continue;
4853 }
4854 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004855 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004856 eol_cnt--;
4857 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004858 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004859 }
4860
4861 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004862 /* Note: we got EOF, and we just close the read end of the pipe.
4863 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004864 * Try these:
4865 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4866 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004867 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004868 fclose(pf);
4869 debug_printf("closed FILE from child. return 0\n");
4870 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004871}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004872#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004873
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004874static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004875 struct in_str *input, int ch)
4876{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004877 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004878 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004879 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004880 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004881 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004882 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004883
4884 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004885#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004886 if (ch == '(' && !dest->o_quoted) {
4887 if (dest->length)
Denis Vlasenkobb929512009-04-16 10:59:40 +00004888 if (done_word(dest, ctx))
4889 return 1;
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004890 if (!command->argv)
4891 goto skip; /* (... */
4892 if (command->argv[1]) { /* word word ... (... */
4893 syntax_error_unexpected_ch('(');
4894 return 1;
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004895 }
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00004896 /* it is "word(..." or "word (..." */
4897 do
4898 ch = i_getch(input);
4899 while (ch == ' ' || ch == '\t');
4900 if (ch != ')') {
4901 syntax_error_unexpected_ch(ch);
4902 return 1;
4903 }
4904 nommu_addchr(&ctx->as_string, ch);
4905 do
4906 ch = i_getch(input);
4907 while (ch == ' ' || ch == '\t' || ch == '\n');
4908 if (ch != '{') {
4909 syntax_error_unexpected_ch(ch);
4910 return 1;
4911 }
4912 nommu_addchr(&ctx->as_string, ch);
4913 command->grp_type = GRP_FUNCTION;
4914 goto skip;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004915 }
4916#endif
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004917 if (command->argv /* word [word]{... */
4918 || dest->length /* word{... */
4919 || dest->o_quoted /* ""{... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004920 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004921 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004922 debug_printf_parse("parse_group return 1: "
4923 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004924 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004925 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004926
4927#if ENABLE_HUSH_FUNCTIONS
4928 skip:
4929#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004930 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004931 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004932 endch = ')';
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004933 command->grp_type = GRP_SUBSHELL;
Denis Vlasenkof8c1f022009-04-17 11:55:42 +00004934 } else {
4935 /* bash does not allow "{echo...", requires whitespace */
4936 ch = i_getch(input);
4937 if (ch != ' ' && ch != '\t' && ch != '\n') {
4938 syntax_error_unexpected_ch(ch);
4939 return 1;
4940 }
4941 nommu_addchr(&ctx->as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004942 }
Denis Vlasenkob7d8c0d2009-04-10 19:05:43 +00004943
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004944 {
4945#if !BB_MMU
4946 char *as_string = NULL;
4947#endif
4948 pipe_list = parse_stream(&as_string, input, endch);
4949#if !BB_MMU
4950 if (as_string)
4951 o_addstr(&ctx->as_string, as_string);
4952#endif
4953 /* empty ()/{} or parse error? */
4954 if (!pipe_list || pipe_list == ERR_PTR) {
Denis Vlasenkobb929512009-04-16 10:59:40 +00004955 /* parse_stream already emitted error msg */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004956#if !BB_MMU
4957 free(as_string);
4958#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004959 debug_printf_parse("parse_group return 1: "
4960 "parse_stream returned %p\n", pipe_list);
4961 return 1;
4962 }
4963 command->group = pipe_list;
4964#if !BB_MMU
4965 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4966 command->group_as_string = as_string;
4967 debug_printf_parse("end of group, remembering as:'%s'\n",
4968 command->group_as_string);
4969#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004970 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004971 debug_printf_parse("parse_group return 0\n");
4972 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004973 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004974}
4975
Mike Frysinger98c52642009-04-02 10:02:37 +00004976#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004977/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004978static void add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004979/* '...' */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004980static void add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004981{
4982 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004983 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004984 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004985 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004986 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004987 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004988 if (ch == '\'')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004989 return;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004990 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004991 }
4992}
4993/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00004994static void add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004995{
4996 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004997 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004998 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004999 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005000 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005001 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005002 if (ch == '"')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005003 return;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005004 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005005 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005006 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005007 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005008 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005009 if (ch == '`') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005010 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005011 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005012 continue;
5013 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00005014 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005015 }
5016}
5017/* Process `cmd` - copy contents until "`" is seen. Complicated by
5018 * \` quoting.
5019 * "Within the backquoted style of command substitution, backslash
5020 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
5021 * The search for the matching backquote shall be satisfied by the first
5022 * backquote found without a preceding backslash; during this search,
5023 * if a non-escaped backquote is encountered within a shell comment,
5024 * a here-document, an embedded command substitution of the $(command)
5025 * form, or a quoted string, undefined results occur. A single-quoted
5026 * or double-quoted string that begins, but does not end, within the
5027 * "`...`" sequence produces undefined results."
5028 * Example Output
5029 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
5030 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005031static void add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005032{
5033 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005034 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005035 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005036 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005037 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005038 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005039 if (ch == '`')
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005040 return;
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005041 if (ch == '\\') {
5042 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005043 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005044 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005045 syntax_error_unterm_ch('`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005046 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005047 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005048 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005049 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005050 ch = ch2;
5051 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005052 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005053 }
5054}
5055/* Process $(cmd) - copy contents until ")" is seen. Complicated by
5056 * quoting and nested ()s.
5057 * "With the $(command) style of command substitution, all characters
5058 * following the open parenthesis to the matching closing parenthesis
5059 * constitute the command. Any valid shell script can be used for command,
5060 * except a script consisting solely of redirections which produces
5061 * unspecified results."
5062 * Example Output
5063 * echo $(echo '(TEST)' BEST) (TEST) BEST
5064 * echo $(echo 'TEST)' BEST) TEST) BEST
5065 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
5066 */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005067static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005068{
5069 int count = 0;
5070 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005071 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005072 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005073 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005074 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005075 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005076 if (ch == '(')
5077 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005078 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005079 if (--count < 0) {
5080 if (!dbl)
5081 break;
5082 if (i_peek(input) == ')') {
5083 i_getch(input);
5084 break;
5085 }
5086 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005087 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005088 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005089 if (ch == '\'') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005090 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005091 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005092 continue;
5093 }
5094 if (ch == '"') {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005095 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005096 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005097 continue;
5098 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005099 if (ch == '\\') {
5100 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005101 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005102 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005103 syntax_error_unterm_ch(')');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005104 /*xfunc_die(); - redundant */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005105 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00005106 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005107 continue;
5108 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005109 }
5110}
Mike Frysinger98c52642009-04-02 10:02:37 +00005111#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005112
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005113/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005114#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005115#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005116 handle_dollar(dest, input)
5117#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005118static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005119 o_string *dest,
5120 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00005121{
Mike Frysinger6379bb42009-03-28 18:55:03 +00005122 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005123 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005124 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005125
5126 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005127 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005128 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005129 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00005130 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005131 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005132 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005133 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005134 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00005135 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005136 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005137 if (!isalnum(ch) && ch != '_')
5138 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005139 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005140 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005141 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005142 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005143 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005144 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005145 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005146 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005147 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00005148 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005149 o_addchr(dest, ch | quote_mask);
5150 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005151 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005152 case '$': /* pid */
5153 case '!': /* last bg pid */
5154 case '?': /* last exit code */
5155 case '#': /* number of args */
5156 case '*': /* args */
5157 case '@': /* args */
5158 goto make_one_char_var;
5159 case '{': {
5160 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00005161
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005162 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005163 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005164 nommu_addchr(as_string, ch);
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00005165 /* TODO: maybe someone will try to escape the '}' */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005166 expansion = 0;
5167 first_char = true;
5168 all_digits = false;
5169 while (1) {
5170 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005171 nommu_addchr(as_string, ch);
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005172 if (ch == '}') {
Mike Frysinger98c52642009-04-02 10:02:37 +00005173 break;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005174 }
Mike Frysinger98c52642009-04-02 10:02:37 +00005175
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005176 if (first_char) {
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005177 if (ch == '#') {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005178 /* ${#var}: length of var contents */
5179 goto char_ok;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005180 }
5181 if (isdigit(ch)) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005182 all_digits = true;
5183 goto char_ok;
5184 }
5185 }
5186
5187 if (expansion < 2
5188 && ( (all_digits && !isdigit(ch))
5189 || (!all_digits && !isalnum(ch) && ch != '_')
5190 )
5191 ) {
5192 /* handle parameter expansions
5193 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
5194 */
5195 if (first_char)
5196 goto case_default;
5197 switch (ch) {
5198 case ':': /* null modifier */
5199 if (expansion == 0) {
5200 debug_printf_parse(": null modifier\n");
5201 ++expansion;
5202 break;
5203 }
5204 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005205 case '#': /* remove prefix */
5206 case '%': /* remove suffix */
5207 if (expansion == 0) {
5208 debug_printf_parse(": remove suffix/prefix\n");
5209 expansion = 2;
5210 break;
5211 }
5212 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005213 case '-': /* default value */
5214 case '=': /* assign default */
5215 case '+': /* alternative */
5216 case '?': /* error indicate */
5217 debug_printf_parse(": parameter expansion\n");
5218 expansion = 2;
5219 break;
5220 default:
5221 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005222 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005223 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
5224 return 1;
5225 }
5226 }
5227 char_ok:
5228 debug_printf_parse(": '%c'\n", ch);
5229 o_addchr(dest, ch | quote_mask);
5230 quote_mask = 0;
5231 first_char = false;
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005232 } /* while (1) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005233 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5234 break;
5235 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005236#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005237 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005238# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005239 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005240# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005241 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005242 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005243# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005244 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005245 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005246 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005247 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5248 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005249# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005250 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005251# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005252 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005253# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005254 if (as_string) {
5255 o_addstr(as_string, dest->data + pos);
5256 o_addchr(as_string, ')');
5257 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005258 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005259# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005260 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00005261 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00005262 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005263# endif
5264# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005265 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5266 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005267# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005268 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005269# endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005270 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005271# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005272 if (as_string) {
5273 o_addstr(as_string, dest->data + pos);
5274 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005275 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005276# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005277 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005278# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005279 break;
5280 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00005281#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005282 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005283 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005284 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005285 ch = i_peek(input);
5286 if (isalnum(ch)) { /* it's $_name or $_123 */
5287 ch = '_';
5288 goto make_var;
5289 }
5290 /* else: it's $_ */
5291 /* TODO: */
5292 /* $_ Shell or shell script name; or last cmd name */
5293 /* $- Option flags set by set builtin or shell options (-i etc) */
5294 default:
5295 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00005296 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00005297 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00005298 return 0;
5299}
5300
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005301#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005302#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005303 parse_stream_dquoted(dest, input, dquote_end)
5304#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005305static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005306 o_string *dest,
5307 struct in_str *input,
5308 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005309{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005310 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005311 int next;
5312
5313 again:
5314 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005315 if (ch != EOF)
5316 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005317 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005318 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005319 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005320 debug_printf_parse("parse_stream_dquoted return 0\n");
5321 return 0;
5322 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005323 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005324 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005325 syntax_error_unterm_ch('"');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005326 /*xfunc_die(); - redundant */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005327 }
5328 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005329 if (ch != '\n') {
5330 next = i_peek(input);
5331 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005332 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5333 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005334 if (ch == '\\') {
5335 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005336 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005337 xfunc_die();
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005338 }
5339 /* bash:
5340 * "The backslash retains its special meaning [in "..."]
5341 * only when followed by one of the following characters:
5342 * $, `, ", \, or <newline>. A double quote may be quoted
5343 * within double quotes by preceding it with a backslash.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005344 */
5345 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko57293002009-04-26 20:06:14 +00005346 ch = i_getch(input);
5347 o_addqchr(dest, ch);
5348 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005349 } else {
5350 o_addqchr(dest, '\\');
Denis Vlasenko57293002009-04-26 20:06:14 +00005351 nommu_addchr(as_string, '\\');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005352 }
5353 goto again;
5354 }
5355 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005356 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005357 debug_printf_parse("parse_stream_dquoted return 1: "
5358 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005359 return 1;
5360 }
5361 goto again;
5362 }
5363#if ENABLE_HUSH_TICK
5364 if (ch == '`') {
5365 //int pos = dest->length;
5366 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5367 o_addchr(dest, 0x80 | '`');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005368 add_till_backquote(dest, input);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005369 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5370 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00005371 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005372 }
5373#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00005374 o_addQchr(dest, ch);
5375 if (ch == '='
5376 && (dest->o_assignment == MAYBE_ASSIGNMENT
5377 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005378 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00005379 ) {
5380 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5381 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005382 goto again;
5383}
5384
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005385/*
5386 * Scan input until EOF or end_trigger char.
5387 * Return a list of pipes to execute, or NULL on EOF
5388 * or if end_trigger character is met.
5389 * On syntax error, exit is shell is not interactive,
5390 * reset parsing machinery and start parsing anew,
5391 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005392 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005393static struct pipe *parse_stream(char **pstring,
5394 struct in_str *input,
5395 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005396{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005397 struct parse_context ctx;
5398 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005399 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005400 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00005401
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00005402 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00005403 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005404 * found. When recursing, quote state is passed in via dest->o_escape.
5405 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005406 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5407 end_trigger ? : 'X');
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005408 debug_enter();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005409
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005410 G.ifs = get_local_var_value("IFS");
5411 if (G.ifs == NULL)
5412 G.ifs = " \t\n";
5413
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005414 reset:
5415#if ENABLE_HUSH_INTERACTIVE
5416 input->promptmode = 0; /* PS1 */
5417#endif
5418 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5419 initialize_context(&ctx);
5420 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005421 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005422 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005423 const char *is_ifs;
5424 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005425 int ch;
5426 int next;
5427 int redir_fd;
5428 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005429
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005430 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005431 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005432 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005433 goto parse_error;
5434 }
5435 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005436 is_in_dquote = 0;
5437 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005438 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005439 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5440 ch, ch, dest.o_escape);
5441 if (ch == EOF) {
5442 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005443
5444 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005445 syntax_error_unterm_str("here document");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005446 xfunc_die();
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005447 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005448 if (done_word(&dest, &ctx)) {
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005449 xfunc_die();
Denis Vlasenko55789c62008-06-18 16:30:42 +00005450 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005451 o_free(&dest);
5452 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005453 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005454 /* If we got nothing... */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005455 /* (this makes bare "&" cmd a no-op.
5456 * bash says: "syntax error near unexpected token '&'") */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005457 if (pi->num_cmds == 0
5458 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5459 ) {
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005460 free_pipe_list(pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005461 pi = NULL;
5462 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005463#if !BB_MMU
5464 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5465 if (pstring)
5466 *pstring = ctx.as_string.data;
5467 else
5468 o_free_unsafe(&ctx.as_string);
5469#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005470 debug_leave();
5471 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005472 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005473 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005474 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005475 is_ifs = strchr(G.ifs, ch);
5476 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005477 "\\$\"" IF_HUSH_TICK("`") /* always special */
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005478 , ch);
5479
5480 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkobf25fbc2009-04-19 13:57:51 +00005481 ordinary_char:
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005482 o_addQchr(&dest, ch);
5483 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5484 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005485 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005486 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005487 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005488 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005489 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005490 continue;
5491 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005492
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005493 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005494 if (done_word(&dest, &ctx)) {
5495 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005496 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005497 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005498#if ENABLE_HUSH_CASE
5499 /* "case ... in <newline> word) ..." -
5500 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005501 if (ctx.command->argv == NULL
5502 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005503 ) {
5504 continue;
5505 }
5506#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005507 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005508 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005509 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5510 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005511 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005512 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005513 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005514 heredoc_cnt = 0;
5515 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005516 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005517 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005518 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005519 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005520 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005521 }
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005522
5523 /* "cmd}" or "cmd }..." without semicolon or &:
5524 * } is an ordinary char in this case, even inside { cmd; }
5525 * Pathological example: { ""}; } should exec "}" cmd
5526 */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005527 if (ch == '}') {
5528 if (!IS_NULL_CMD(ctx.command) /* cmd } */
5529 || dest.length != 0 /* word} */
5530 || dest.o_quoted /* ""} */
5531 ) {
5532 goto ordinary_char;
5533 }
5534 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
5535 goto skip_end_trigger;
5536 /* else: } does terminate a group */
Denis Vlasenko9f8d9382009-04-19 14:03:11 +00005537 }
5538
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005539 if (end_trigger && end_trigger == ch
5540 && (heredoc_cnt == 0 || end_trigger != ';')
5541 ) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005542 if (heredoc_cnt) {
5543 /* This is technically valid:
5544 * { cat <<HERE; }; echo Ok
5545 * heredoc
5546 * heredoc
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005547 * HERE
5548 * but we don't support this.
5549 * We require heredoc to be in enclosing {}/(),
5550 * if any.
5551 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005552 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005553 goto parse_error;
5554 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005555 if (done_word(&dest, &ctx)) {
5556 goto parse_error;
5557 }
5558 done_pipe(&ctx, PIPE_SEQ);
5559 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005560 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005561 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005562 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005563 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005564 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005565#if !BB_MMU
5566 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5567 if (pstring)
5568 *pstring = ctx.as_string.data;
5569 else
5570 o_free_unsafe(&ctx.as_string);
5571#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005572 debug_leave();
5573 debug_printf_parse("parse_stream return %p: "
5574 "end_trigger char found\n",
5575 ctx.list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005576 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005577 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005578 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00005579 skip_end_trigger:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005580 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005581 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005582
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005583 next = '\0';
5584 if (ch != '\n') {
5585 next = i_peek(input);
5586 }
5587
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005588 /* Catch <, > before deciding whether this word is
5589 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5590 switch (ch) {
5591 case '>':
5592 redir_fd = redirect_opt_num(&dest);
5593 if (done_word(&dest, &ctx)) {
5594 goto parse_error;
5595 }
5596 redir_style = REDIRECT_OVERWRITE;
5597 if (next == '>') {
5598 redir_style = REDIRECT_APPEND;
5599 ch = i_getch(input);
5600 nommu_addchr(&ctx.as_string, ch);
5601 }
5602#if 0
5603 else if (next == '(') {
5604 syntax_error(">(process) not supported");
5605 goto parse_error;
5606 }
5607#endif
5608 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5609 goto parse_error;
5610 continue; /* back to top of while (1) */
5611 case '<':
5612 redir_fd = redirect_opt_num(&dest);
5613 if (done_word(&dest, &ctx)) {
5614 goto parse_error;
5615 }
5616 redir_style = REDIRECT_INPUT;
5617 if (next == '<') {
5618 redir_style = REDIRECT_HEREDOC;
5619 heredoc_cnt++;
5620 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5621 ch = i_getch(input);
5622 nommu_addchr(&ctx.as_string, ch);
5623 } else if (next == '>') {
5624 redir_style = REDIRECT_IO;
5625 ch = i_getch(input);
5626 nommu_addchr(&ctx.as_string, ch);
5627 }
5628#if 0
5629 else if (next == '(') {
5630 syntax_error("<(process) not supported");
5631 goto parse_error;
5632 }
5633#endif
5634 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5635 goto parse_error;
5636 continue; /* back to top of while (1) */
5637 }
5638
5639 if (dest.o_assignment == MAYBE_ASSIGNMENT
5640 /* check that we are not in word in "a=1 2>word b=1": */
5641 && !ctx.pending_redirect
5642 ) {
5643 /* ch is a special char and thus this word
5644 * cannot be an assignment */
5645 dest.o_assignment = NOT_ASSIGNMENT;
5646 }
5647
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005648 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00005649 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005650 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005651 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005652 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005653 if (ch == EOF || ch == '\n')
5654 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005655 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005656 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005657 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005658 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00005659 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005660 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005661 }
5662 break;
5663 case '\\':
5664 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005665 syntax_error("\\<eof>");
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005666 xfunc_die();
Eric Andersen25f27032001-04-26 23:22:31 +00005667 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005668 o_addchr(&dest, '\\');
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005669 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005670 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005671 o_addchr(&dest, ch);
5672 /* Example: echo Hello \2>file
5673 * we need to know that word 2 is quoted */
5674 dest.o_quoted = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005675 break;
5676 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005677 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005678 debug_printf_parse("parse_stream parse error: "
5679 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005680 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005681 }
Eric Andersen25f27032001-04-26 23:22:31 +00005682 break;
5683 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005684 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005685 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005686 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005687 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005688 syntax_error_unterm_ch('\'');
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005689 /*xfunc_die(); - redundant */
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005690 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005691 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005692 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005693 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005694 if (dest.o_assignment == NOT_ASSIGNMENT)
5695 o_addqchr(&dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005696 else
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005697 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005698 }
Eric Andersen25f27032001-04-26 23:22:31 +00005699 break;
5700 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005701 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005702 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005703 if (dest.o_assignment == NOT_ASSIGNMENT)
5704 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005705 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005706#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005707 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005708#if !BB_MMU
5709 int pos;
5710#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005711 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5712 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005713#if !BB_MMU
5714 pos = dest.length;
5715#endif
Denis Vlasenko0b677d82009-04-10 13:49:10 +00005716 add_till_backquote(&dest, input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005717#if !BB_MMU
5718 o_addstr(&ctx.as_string, dest.data + pos);
5719 o_addchr(&ctx.as_string, '`');
5720#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005721 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5722 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005723 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005724 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005725#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005726 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005727#if ENABLE_HUSH_CASE
5728 case_semi:
5729#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005730 if (done_word(&dest, &ctx)) {
5731 goto parse_error;
5732 }
5733 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005734#if ENABLE_HUSH_CASE
5735 /* Eat multiple semicolons, detect
5736 * whether it means something special */
5737 while (1) {
5738 ch = i_peek(input);
5739 if (ch != ';')
5740 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005741 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005742 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005743 if (ctx.ctx_res_w == RES_CASEI) {
5744 ctx.ctx_dsemicolon = 1;
5745 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005746 break;
5747 }
5748 }
5749#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005750 new_cmd:
5751 /* We just finished a cmd. New one may start
5752 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005753 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00005754 break;
5755 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005756 if (done_word(&dest, &ctx)) {
5757 goto parse_error;
5758 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005759 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005760 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005761 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005762 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005763 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005764 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005765 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005766 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005767 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005768 if (done_word(&dest, &ctx)) {
5769 goto parse_error;
5770 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005771#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005772 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005773 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005774#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005775 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005776 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005777 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005778 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005779 } else {
5780 /* we could pick up a file descriptor choice here
5781 * with redirect_opt_num(), but bash doesn't do it.
5782 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005783 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005784 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005785 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005786 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005787#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005788 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005789 if (ctx.ctx_res_w == RES_MATCH
5790 && ctx.command->argv == NULL /* not (word|(... */
5791 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005792 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005793 ) {
5794 continue;
5795 }
5796#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005797 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005798 if (parse_group(&dest, &ctx, input, ch) != 0) {
5799 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005800 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005801 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005802 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005803#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005804 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005805 goto case_semi;
5806#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005807 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005808 /* proper use of this character is caught by end_trigger:
5809 * if we see {, we call parse_group(..., end_trigger='}')
5810 * and it will match } earlier (not here). */
Denis Vlasenkoc0ea3292009-04-10 21:22:02 +00005811 syntax_error_unexpected_ch(ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005812 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005813 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005814 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005815 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005816 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005817 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005818
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005819 parse_error:
5820 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005821 struct parse_context *pctx;
5822 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005823
5824 /* Clean up allocated tree.
5825 * Samples for finding leaks on syntax error recovery path.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005826 * Run them from interactive shell, watch pmap `pidof hush`.
5827 * while if false; then false; fi do break; done
5828 * (bash accepts it)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005829 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005830 * Samples to catch leaks at execution:
5831 * while if (true | {true;}); then echo ok; fi; do break; done
5832 * 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 +00005833 */
5834 pctx = &ctx;
5835 do {
5836 /* Update pipe/command counts,
5837 * otherwise freeing may miss some */
5838 done_pipe(pctx, PIPE_SEQ);
5839 debug_printf_clean("freeing list %p from ctx %p\n",
5840 pctx->list_head, pctx);
5841 debug_print_tree(pctx->list_head, 0);
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005842 free_pipe_list(pctx->list_head);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005843 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005844#if !BB_MMU
5845 o_free_unsafe(&pctx->as_string);
5846#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005847 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005848 if (pctx != &ctx) {
5849 free(pctx);
5850 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005851 IF_HAS_KEYWORDS(pctx = p2;)
5852 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005853 /* Free text, clear all dest fields */
5854 o_free(&dest);
5855 /* If we are not in top-level parse, we return,
5856 * our caller will propagate error.
5857 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005858 if (end_trigger != ';') {
5859#if !BB_MMU
5860 if (pstring)
5861 *pstring = NULL;
5862#endif
Denis Vlasenko0701dca2009-04-11 10:38:47 +00005863 debug_leave();
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005864 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005865 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005866 /* Discard cached input, force prompt */
5867 input->p = NULL;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00005868 IF_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005869 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005870 }
Eric Andersen25f27032001-04-26 23:22:31 +00005871}
5872
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005873/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005874 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5875 * end_trigger controls how often we stop parsing
5876 * NUL: parse all, execute, return
5877 * ';': parse till ';' or newline, execute, repeat till EOF
5878 */
5879static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005880{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005881 while (1) {
5882 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005883
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005884 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005885 if (!pipe_list) /* EOF */
5886 break;
5887 debug_print_tree(pipe_list, 0);
5888 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5889 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005890 }
Eric Andersen25f27032001-04-26 23:22:31 +00005891}
5892
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005893static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005894{
5895 struct in_str input;
5896 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005897 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005898}
5899
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005900static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005901{
Eric Andersen25f27032001-04-26 23:22:31 +00005902 struct in_str input;
5903 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005904 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005905}
5906
Denis Vlasenkof9375282009-04-05 19:13:39 +00005907/* Called a few times only (or even once if "sh -c") */
5908static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00005909{
Denis Vlasenkof9375282009-04-05 19:13:39 +00005910 unsigned sig;
5911 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005912
Denis Vlasenkof9375282009-04-05 19:13:39 +00005913 mask = (1 << SIGQUIT);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00005914 if (G_interactive_fd) {
Denis Vlasenkoe4bd4f22009-04-17 13:52:51 +00005915 mask = (1 << SIGQUIT) | SPECIAL_INTERACTIVE_SIGS;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00005916 if (G.saved_tty_pgrp) /* we have ctty, job control sigs work */
5917 mask |= SPECIAL_JOB_SIGS;
5918 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005919 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00005920
Denis Vlasenkof9375282009-04-05 19:13:39 +00005921 if (!second_time)
5922 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5923 sig = 0;
5924 while (mask) {
5925 if (mask & 1)
5926 sigaddset(&G.blocked_set, sig);
5927 mask >>= 1;
5928 sig++;
5929 }
5930 sigdelset(&G.blocked_set, SIGCHLD);
5931
5932 sigprocmask(SIG_SETMASK, &G.blocked_set,
5933 second_time ? NULL : &G.inherited_set);
5934 /* POSIX allows shell to re-enable SIGCHLD
5935 * even if it was SIG_IGN on entry */
5936// G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5937 if (!second_time)
5938 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5939}
5940
5941#if ENABLE_HUSH_JOB
5942/* helper */
5943static void maybe_set_to_sigexit(int sig)
5944{
5945 void (*handler)(int);
5946 /* non_DFL_mask'ed signals are, well, masked,
5947 * no need to set handler for them.
5948 */
5949 if (!((G.non_DFL_mask >> sig) & 1)) {
5950 handler = signal(sig, sigexit);
5951 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5952 signal(sig, handler);
5953 }
5954}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005955/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005956static void set_fatal_handlers(void)
5957{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00005958 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005959 if (HUSH_DEBUG) {
5960 maybe_set_to_sigexit(SIGILL );
5961 maybe_set_to_sigexit(SIGFPE );
5962 maybe_set_to_sigexit(SIGBUS );
5963 maybe_set_to_sigexit(SIGSEGV);
5964 maybe_set_to_sigexit(SIGTRAP);
5965 } /* else: hush is perfect. what SEGV? */
5966 maybe_set_to_sigexit(SIGABRT);
5967 /* bash 3.2 seems to handle these just like 'fatal' ones */
5968 maybe_set_to_sigexit(SIGPIPE);
5969 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00005970 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00005971 * if we aren't interactive... but in this case
5972 * we never want to restore pgrp on exit, and this fn is not called */
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00005973 /*maybe_set_to_sigexit(SIGHUP );*/
Denis Vlasenkof9375282009-04-05 19:13:39 +00005974 /*maybe_set_to_sigexit(SIGTERM);*/
5975 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00005976}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005977#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00005978
Denis Vlasenkod5762932009-03-31 11:22:57 +00005979static int set_mode(const char cstate, const char mode)
5980{
5981 int state = (cstate == '-' ? 1 : 0);
5982 switch (mode) {
5983 case 'n': G.fake_mode = state; break;
5984 case 'x': /*G.debug_mode = state;*/ break;
5985 default: return EXIT_FAILURE;
5986 }
5987 return EXIT_SUCCESS;
5988}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005989
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00005990int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00005991int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00005992{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005993 static const struct variable const_shell_ver = {
5994 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005995 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005996 .max_len = 1, /* 0 can provoke free(name) */
5997 .flg_export = 1,
5998 .flg_read_only = 1,
5999 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00006000 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00006001 int opt;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006002 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006003 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00006004
Denis Vlasenko574f2f42008-02-27 18:41:59 +00006005 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006006 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006007 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006008#if !BB_MMU
6009 G.argv0_for_re_execing = argv[0];
6010#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006011 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006012 G.shell_ver = const_shell_ver; /* copying struct here */
6013 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006014 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006015 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
6016 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006017 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006018 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00006019 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006020 if (e) while (*e) {
6021 char *value = strchr(*e, '=');
6022 if (value) { /* paranoia */
6023 cur_var->next = xzalloc(sizeof(*cur_var));
6024 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006025 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006026 cur_var->max_len = strlen(*e);
6027 cur_var->flg_export = 1;
6028 }
6029 e++;
6030 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006031 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00006032 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenko38f63192007-01-22 09:03:07 +00006033#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00006034 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00006035#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00006036 G.global_argc = argc;
6037 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00006038 /* Initialize some more globals to non-zero values */
6039 set_cwd();
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006040 cmdedit_update_prompt();
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00006041
Denis Vlasenkoed782372009-04-10 00:45:02 +00006042 if (setjmp(die_jmp)) {
6043 /* xfunc has failed! die die die */
6044 /* no EXIT traps, this is an escape hatch! */
6045 G.exiting = 1;
6046 hush_exit(xfunc_error_retval);
6047 }
6048
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006049 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006050 * block_signals(0) if we are going to execute "sh <script>",
6051 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006052 * If we later decide that we are interactive, we run block_signals(0)
6053 * (or re-run block_signals(1) if we ran block_signals(0) before)
6054 * in order to intercept (more) signals.
6055 */
6056
6057 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006058 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006059 while (1) {
6060 opt = getopt(argc, argv, "c:xins"
6061#if !BB_MMU
Denis Vlasenkobc569742009-04-12 20:35:19 +00006062 "<:$:R:V:"
6063# if ENABLE_HUSH_FUNCTIONS
6064 "F:"
6065# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006066#endif
6067 );
6068 if (opt <= 0)
6069 break;
Eric Andersen25f27032001-04-26 23:22:31 +00006070 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006071 case 'c':
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006072 if (!G.root_pid)
6073 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00006074 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00006075 if (!argv[optind]) {
6076 /* -c 'script' (no params): prevent empty $0 */
6077 *--G.global_argv = argv[0];
6078 optind--;
6079 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00006080 G.global_argc = argc - optind;
Denis Vlasenkof9375282009-04-05 19:13:39 +00006081 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006082 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006083 goto final_return;
6084 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00006085 /* Well, we cannot just declare interactiveness,
6086 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006087 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006088 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00006089 case 's':
6090 /* "-s" means "read from stdin", but this is how we always
6091 * operate, so simply do nothing here. */
6092 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006093#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00006094 case '<': /* "big heredoc" support */
6095 full_write(STDOUT_FILENO, optarg, strlen(optarg));
6096 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006097 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006098 G.root_pid = bb_strtou(optarg, &optarg, 16);
6099 optarg++;
6100 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
6101 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006102 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006103# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006104 optarg++;
6105 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006106# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00006107 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006108 case 'R':
6109 case 'V':
6110 set_local_var(xstrdup(optarg), 0, opt == 'R');
6111 break;
Denis Vlasenkobc569742009-04-12 20:35:19 +00006112# if ENABLE_HUSH_FUNCTIONS
6113 case 'F': {
6114 struct function *funcp = new_function(optarg);
6115 /* funcp->name is already set to optarg */
6116 /* funcp->body is set to NULL. It's a special case. */
6117 funcp->body_as_string = argv[optind];
6118 optind++;
6119 break;
6120 }
6121# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006122#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006123 case 'n':
6124 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00006125 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006126 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006127 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006128#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006129 fprintf(stderr, "Usage: sh [FILE]...\n"
6130 " or: sh -c command [args]...\n\n");
6131 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006132#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006133 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00006134#endif
Eric Andersen25f27032001-04-26 23:22:31 +00006135 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006136 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006137
6138 if (!G.root_pid)
6139 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00006140
6141 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006142 if (argv[0] && argv[0][0] == '-') {
6143 FILE *input;
Denis Vlasenko4ea187f2009-04-17 14:35:43 +00006144 /* TODO: what should argv be while sourcing /etc/profile? */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006145 debug_printf("sourcing /etc/profile\n");
6146 input = fopen_for_read("/etc/profile");
6147 if (input != NULL) {
6148 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00006149 block_signals(0); /* 0: called 1st time */
6150 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006151 parse_and_run_file(input);
6152 fclose(input);
6153 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006154 /* bash: after sourcing /etc/profile,
6155 * tries to source (in the given order):
6156 * ~/.bash_profile, ~/.bash_login, ~/.profile,
6157 * stopping of first found. --noprofile turns this off.
6158 * bash also sources ~/.bash_logout on exit.
6159 * If called as sh, skips .bash_XXX files.
6160 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00006161 }
6162
Denis Vlasenkof9375282009-04-05 19:13:39 +00006163 if (argv[optind]) {
6164 FILE *input;
6165 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00006166 * "bash <script>" (which is never interactive (unless -i?))
6167 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00006168 * If called as sh, does the same but with $ENV.
6169 */
6170 debug_printf("running script '%s'\n", argv[optind]);
6171 G.global_argv = argv + optind;
6172 G.global_argc = argc - optind;
6173 input = xfopen_for_read(argv[optind]);
6174 close_on_exec_on(fileno(input));
6175 if (!signal_mask_is_inited)
6176 block_signals(0); /* 0: called 1st time */
6177 parse_and_run_file(input);
6178#if ENABLE_FEATURE_CLEAN_UP
6179 fclose(input);
6180#endif
6181 goto final_return;
6182 }
6183
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00006184 /* Up to here, shell was non-interactive. Now it may become one.
6185 * NB: don't forget to (re)run block_signals(0/1) as needed.
6186 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006187
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00006188 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00006189 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00006190 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00006191 * no arguments remaining or the -s flag given
6192 * standard input is a terminal
6193 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00006194 * Refer to Posix.2, the description of the 'sh' utility.
6195 */
6196#if ENABLE_HUSH_JOB
6197 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006198 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
Denis Vlasenkof9375282009-04-05 19:13:39 +00006199 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006200 if (G.saved_tty_pgrp < 0)
6201 G.saved_tty_pgrp = 0;
6202
6203 /* try to dup stdin to high fd#, >= 255 */
6204 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6205 if (G_interactive_fd < 0) {
6206 /* try to dup to any fd */
6207 G_interactive_fd = dup(STDIN_FILENO);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006208 if (G_interactive_fd < 0) {
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006209 /* give up */
6210 G_interactive_fd = 0;
6211 G.saved_tty_pgrp = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00006212 }
6213 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006214// TODO: track & disallow any attempts of user
6215// to (inadvertently) close/redirect G_interactive_fd
Eric Andersen25f27032001-04-26 23:22:31 +00006216 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006217 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006218 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006219 close_on_exec_on(G_interactive_fd);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006220
6221 if (G.saved_tty_pgrp) {
6222 /* If we were run as 'hush &', sleep until we are
6223 * in the foreground (tty pgrp == our pgrp).
6224 * If we get started under a job aware app (like bash),
6225 * make sure we are now in charge so we don't fight over
6226 * who gets the foreground */
6227 while (1) {
6228 pid_t shell_pgrp = getpgrp();
6229 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
6230 if (G.saved_tty_pgrp == shell_pgrp)
6231 break;
6232 /* send TTIN to ourself (should stop us) */
6233 kill(- shell_pgrp, SIGTTIN);
6234 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00006235 }
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006236
Denis Vlasenkof9375282009-04-05 19:13:39 +00006237 /* Block some signals */
6238 block_signals(signal_mask_is_inited);
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006239
6240 if (G.saved_tty_pgrp) {
6241 /* Set other signals to restore saved_tty_pgrp */
6242 set_fatal_handlers();
6243 /* Put ourselves in our own process group
6244 * (bash, too, does this only if ctty is available) */
6245 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
6246 /* Grab control of the terminal */
6247 tcsetpgrp(G_interactive_fd, getpid());
6248 }
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00006249 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00006250 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00006251 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00006252 } else if (!signal_mask_is_inited) {
6253 block_signals(0); /* 0: called 1st time */
6254 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006255#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00006256 /* No job control compiled in, only prompt/line editing */
6257 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006258 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
6259 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006260 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006261 G_interactive_fd = dup(STDIN_FILENO);
6262 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006263 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006264 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00006265 }
6266 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006267 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00006268 close_on_exec_on(G_interactive_fd);
6269 block_signals(signal_mask_is_inited);
6270 } else if (!signal_mask_is_inited) {
6271 block_signals(0);
6272 }
6273#else
6274 /* We have interactiveness code disabled */
6275 if (!signal_mask_is_inited) {
6276 block_signals(0);
6277 }
6278#endif
6279 /* bash:
6280 * if interactive but not a login shell, sources ~/.bashrc
6281 * (--norc turns this off, --rcfile <file> overrides)
6282 */
6283
6284 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00006285 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysinger26cf2832009-04-24 06:40:30 +00006286 if (ENABLE_HUSH_HELP)
6287 puts("Enter 'help' for a list of built-in commands.");
6288 puts("");
Mike Frysingerb2705e12009-03-23 08:44:02 +00006289 }
6290
Denis Vlasenkof9375282009-04-05 19:13:39 +00006291 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00006292
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006293 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00006294#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00006295 if (G.cwd != bb_msg_unknown)
6296 free((char*)G.cwd);
6297 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006298 while (cur_var) {
6299 struct variable *tmp = cur_var;
6300 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00006301 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00006302 cur_var = cur_var->next;
6303 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00006304 }
Eric Andersen25f27032001-04-26 23:22:31 +00006305#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006306 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00006307}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00006308
6309
6310#if ENABLE_LASH
6311int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6312int lash_main(int argc, char **argv)
6313{
6314 //bb_error_msg("lash is deprecated, please use hush instead");
6315 return hush_main(argc, argv);
6316}
6317#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006318
6319
6320/*
6321 * Built-ins
6322 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006323static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006324{
6325 return 0;
6326}
6327
6328static int builtin_test(char **argv)
6329{
6330 int argc = 0;
6331 while (*argv) {
6332 argc++;
6333 argv++;
6334 }
6335 return test_main(argc, argv - argc);
6336}
6337
6338static int builtin_echo(char **argv)
6339{
6340 int argc = 0;
6341 while (*argv) {
6342 argc++;
6343 argv++;
6344 }
6345 return echo_main(argc, argv - argc);
6346}
6347
6348static int builtin_eval(char **argv)
6349{
6350 int rcode = EXIT_SUCCESS;
6351
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006352 if (*++argv) {
6353 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006354 /* bash:
6355 * eval "echo Hi; done" ("done" is syntax error):
6356 * "echo Hi" will not execute too.
6357 */
6358 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006359 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006360 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006361 }
6362 return rcode;
6363}
6364
6365static int builtin_cd(char **argv)
6366{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006367 const char *newdir = argv[1];
6368 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006369 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006370 * bash says "bash: cd: HOME not set" and does nothing
6371 * (exitcode 1)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006372 */
Mike Frysinger67c1c7b2009-04-24 06:26:18 +00006373 newdir = get_local_var_value("HOME") ? : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006374 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006375 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006376 /* Mimic bash message exactly */
6377 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006378 return EXIT_FAILURE;
6379 }
6380 set_cwd();
6381 return EXIT_SUCCESS;
6382}
6383
6384static int builtin_exec(char **argv)
6385{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006386 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006387 return EXIT_SUCCESS; /* bash does this */
6388 {
6389#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00006390 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006391#endif
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006392 /* TODO: if exec fails, bash does NOT exit! We do... */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006393 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006394 /* never returns */
6395 }
6396}
6397
6398static int builtin_exit(char **argv)
6399{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006400 debug_printf_exec("%s()\n", __func__);
Denis Vlasenko40e84372009-04-18 11:23:38 +00006401
6402 /* interactive bash:
6403 * # trap "echo EEE" EXIT
6404 * # exit
6405 * exit
6406 * There are stopped jobs.
6407 * (if there are _stopped_ jobs, running ones don't count)
6408 * # exit
6409 * exit
6410 # EEE (then bash exits)
6411 *
6412 * we can use G.exiting = -1 as indicator "last cmd was exit"
6413 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006414
6415 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006416 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006417 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006418 /* mimic bash: exit 123abc == exit 255 + error msg */
6419 xfunc_error_retval = 255;
6420 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006421 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006422}
6423
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006424static void print_escaped(const char *s)
6425{
6426 do {
6427 if (*s != '\'') {
6428 const char *p;
6429
6430 p = strchrnul(s, '\'');
6431 /* print 'xxxx', possibly just '' */
6432 printf("'%.*s'", (int)(p - s), s);
6433 if (*p == '\0')
6434 break;
6435 s = p;
6436 }
6437 /* s points to '; print "'''...'''" */
6438 putchar('"');
6439 do putchar('\''); while (*++s == '\'');
6440 putchar('"');
6441 } while (*s);
6442}
6443
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006444static int builtin_export(char **argv)
6445{
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006446 unsigned opt_unexport;
6447
6448 if (argv[1] == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006449 char **e = environ;
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006450 if (e) {
6451 while (*e) {
6452#if 0
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006453 puts(*e++);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006454#else
6455 /* ash emits: export VAR='VAL'
6456 * bash: declare -x VAR="VAL"
6457 * we follow ash example */
6458 const char *s = *e++;
6459 const char *p = strchr(s, '=');
6460
6461 if (!p) /* wtf? take next variable */
6462 continue;
6463 /* export var= */
6464 printf("export %.*s", (int)(p - s) + 1, s);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006465 print_escaped(p + 1);
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006466 putchar('\n');
6467#endif
6468 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006469 /*fflush(stdout); - done after each builtin anyway */
Denis Vlasenko0b677d82009-04-10 13:49:10 +00006470 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006471 return EXIT_SUCCESS;
6472 }
6473
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006474#if ENABLE_HUSH_EXPORT_N
Denis Vlasenko28e67962009-04-26 23:22:40 +00006475 /* "!": do not abort on errors */
6476 /* "+": stop at 1st non-option */
6477 opt_unexport = getopt32(argv, "!+n");
6478 if (opt_unexport == (unsigned)-1)
6479 return EXIT_FAILURE;
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006480 argv += optind;
6481#else
6482 opt_unexport = 0;
6483 argv++;
6484#endif
6485
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006486 do {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006487 char *name = *argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006488
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006489 /* So far we do not check that name is valid (TODO?) */
6490
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006491 if (strchr(name, '=') == NULL) {
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006492 struct variable *var;
6493
6494 var = get_local_var(name);
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006495 if (opt_unexport) {
6496 /* export -n NAME (without =VALUE) */
6497 if (var) {
6498 var->flg_export = 0;
6499 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
6500 unsetenv(name);
6501 } /* else: export -n NOT_EXISTING_VAR: no-op */
6502 continue;
6503 }
6504 /* export NAME (without =VALUE) */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006505 if (var) {
6506 var->flg_export = 1;
6507 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6508 putenv(var->varstr);
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006509 continue;
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006510 }
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006511 /* Exporting non-existing variable.
6512 * bash does not put it in environment,
6513 * but remembers that it is exported,
6514 * and does put it in env when it is set later.
6515 * We just set it to "" and export. */
6516 name = xasprintf("%s=", name);
6517 } else {
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006518 /* (Un)exporting NAME=VALUE */
Denis Vlasenkodcd78c42009-04-19 23:07:51 +00006519 name = xstrdup(name);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006520 }
Denis Vlasenkoad4bd052009-04-20 22:04:21 +00006521 set_local_var(name,
6522 /*export:*/ (opt_unexport ? -1 : 1),
6523 /*readonly:*/ 0
6524 );
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006525 } while (*++argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006526
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006527 return EXIT_SUCCESS;
6528}
6529
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006530static int builtin_trap(char **argv)
6531{
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006532 int sig;
6533 char *new_cmd;
6534
6535 if (!G.traps)
6536 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6537
6538 argv++;
6539 if (!*argv) {
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00006540 int i;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006541 /* No args: print all trapped */
6542 for (i = 0; i < NSIG; ++i) {
6543 if (G.traps[i]) {
6544 printf("trap -- ");
6545 print_escaped(G.traps[i]);
6546 printf(" %s\n", get_signame(i));
6547 }
6548 }
6549 /*fflush(stdout); - done after each builtin anyway */
6550 return EXIT_SUCCESS;
6551 }
6552
6553 new_cmd = NULL;
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006554 /* If first arg is a number: reset all specified signals */
6555 sig = bb_strtou(*argv, NULL, 10);
6556 if (errno == 0) {
6557 int ret;
6558 process_sig_list:
6559 ret = EXIT_SUCCESS;
6560 while (*argv) {
6561 sig = get_signum(*argv++);
6562 if (sig < 0 || sig >= NSIG) {
6563 ret = EXIT_FAILURE;
6564 /* Mimic bash message exactly */
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00006565 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006566 continue;
6567 }
6568
6569 free(G.traps[sig]);
6570 G.traps[sig] = xstrdup(new_cmd);
6571
6572 debug_printf("trap: setting SIG%s (%i) to '%s'",
6573 get_signame(sig), sig, G.traps[sig]);
6574
6575 /* There is no signal for 0 (EXIT) */
6576 if (sig == 0)
6577 continue;
6578
6579 if (new_cmd) {
6580 sigaddset(&G.blocked_set, sig);
6581 } else {
6582 /* There was a trap handler, we are removing it
6583 * (if sig has non-DFL handling,
6584 * we don't need to do anything) */
6585 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6586 continue;
6587 sigdelset(&G.blocked_set, sig);
6588 }
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006589 }
Denis Vlasenko6008d8a2009-04-18 13:05:10 +00006590 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Denis Vlasenko38e626d2009-04-18 12:58:19 +00006591 return ret;
6592 }
6593
6594 if (!argv[1]) { /* no second arg */
6595 bb_error_msg("trap: invalid arguments");
6596 return EXIT_FAILURE;
6597 }
6598
6599 /* First arg is "-": reset all specified to default */
6600 /* First arg is "--": skip it, the rest is "handler SIGs..." */
6601 /* Everything else: set arg as signal handler
6602 * (includes "" case, which ignores signal) */
6603 if (argv[0][0] == '-') {
6604 if (argv[0][1] == '\0') { /* "-" */
6605 /* new_cmd remains NULL: "reset these sigs" */
6606 goto reset_traps;
6607 }
6608 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
6609 argv++;
6610 }
6611 /* else: "-something", no special meaning */
6612 }
6613 new_cmd = *argv;
6614 reset_traps:
6615 argv++;
6616 goto process_sig_list;
6617}
6618
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006619#if ENABLE_HUSH_JOB
6620/* built-in 'fg' and 'bg' handler */
6621static int builtin_fg_bg(char **argv)
6622{
6623 int i, jobnum;
6624 struct pipe *pi;
6625
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006626 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006627 return EXIT_FAILURE;
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006628
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006629 /* If they gave us no args, assume they want the last backgrounded task */
6630 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006631 for (pi = G.job_list; pi; pi = pi->next) {
6632 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006633 goto found;
6634 }
6635 }
6636 bb_error_msg("%s: no current job", argv[0]);
6637 return EXIT_FAILURE;
6638 }
6639 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6640 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6641 return EXIT_FAILURE;
6642 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006643 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006644 if (pi->jobid == jobnum) {
6645 goto found;
6646 }
6647 }
6648 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6649 return EXIT_FAILURE;
6650 found:
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006651 /* TODO: bash prints a string representation
6652 * of job being foregrounded (like "sleep 1 | cat") */
Denis Vlasenkoc8653f62009-04-27 23:29:14 +00006653 if (argv[0][0] == 'f' && G.saved_tty_pgrp) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006654 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006655 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006656 }
6657
6658 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006659 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6660 for (i = 0; i < pi->num_cmds; i++) {
6661 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6662 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006663 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006664 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006665
6666 i = kill(- pi->pgrp, SIGCONT);
6667 if (i < 0) {
6668 if (errno == ESRCH) {
6669 delete_finished_bg_job(pi);
6670 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006671 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006672 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006673 }
6674
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006675 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006676 remove_bg_job(pi);
6677 return checkjobs_and_fg_shell(pi);
6678 }
6679 return EXIT_SUCCESS;
6680}
6681#endif
6682
6683#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006684static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006685{
6686 const struct built_in_command *x;
6687
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006688 printf("\n"
6689 "Built-in commands:\n"
6690 "------------------\n");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006691 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6692 printf("%s\t%s\n", x->cmd, x->descr);
6693 }
6694 printf("\n\n");
6695 return EXIT_SUCCESS;
6696}
6697#endif
6698
6699#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006700static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006701{
6702 struct pipe *job;
6703 const char *status_string;
6704
Denis Vlasenko87a86552008-07-29 19:43:10 +00006705 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006706 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006707 status_string = "Stopped";
6708 else
6709 status_string = "Running";
6710
6711 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6712 }
6713 return EXIT_SUCCESS;
6714}
6715#endif
6716
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00006717#if HUSH_DEBUG
6718static int builtin_memleak(char **argv UNUSED_PARAM)
6719{
6720 void *p;
6721 unsigned long l;
6722
6723 /* Crude attempt to find where "free memory" starts,
6724 * sans fragmentation. */
6725 p = malloc(240);
6726 l = (unsigned long)p;
6727 free(p);
6728 p = malloc(3400);
6729 if (l < (unsigned long)p) l = (unsigned long)p;
6730 free(p);
6731
6732 if (!G.memleak_value)
6733 G.memleak_value = l;
6734
6735 l -= G.memleak_value;
6736 if ((long)l < 0)
6737 l = 0;
6738 l /= 1024;
6739 if (l > 127)
6740 l = 127;
6741
6742 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6743 return l;
6744}
6745#endif
6746
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006747static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006748{
6749 puts(set_cwd());
6750 return EXIT_SUCCESS;
6751}
6752
6753static int builtin_read(char **argv)
6754{
6755 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006756 const char *name = "REPLY";
6757
6758 if (argv[1]) {
6759 name = argv[1];
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006760 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6761 * and _after_ that_ it will complain */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006762 if (!is_well_formed_var_name(name, '\0')) {
6763 /* Mimic bash message */
6764 bb_error_msg("read: '%s': not a valid identifier", name);
6765 return 1;
6766 }
6767 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006768
Denis Vlasenko1fd1ea42009-04-10 12:03:20 +00006769//TODO: bash unbackslashes input, splits words and puts them in argv[i]
6770
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006771 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006772 return set_local_var(string, 0, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006773}
6774
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006775/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6776 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006777 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006778 * set [-abCefhmnuvx] [-o option] [argument...]
6779 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006780 * set -- [argument...]
6781 * set -o
6782 * set +o
6783 * Implementations shall support the options in both their hyphen and
6784 * plus-sign forms. These options can also be specified as options to sh.
6785 * Examples:
6786 * Write out all variables and their values: set
6787 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6788 * Turn on the -x and -v options: set -xv
6789 * Unset all positional parameters: set --
6790 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6791 * Set the positional parameters to the expansion of x, even if x expands
6792 * with a leading '-' or '+': set -- $x
6793 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006794 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006795 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006796static int builtin_set(char **argv)
6797{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006798 int n;
6799 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006800 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006801
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006802 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006803 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00006804 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006805 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006806 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006807 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006808
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006809 do {
6810 if (!strcmp(arg, "--")) {
6811 ++argv;
6812 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006813 }
Denis Vlasenko6ba6f542009-04-10 21:57:50 +00006814 if (arg[0] != '+' && arg[0] != '-')
6815 break;
6816 for (n = 1; arg[n]; ++n)
6817 if (set_mode(arg[0], arg[n]))
6818 goto error;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006819 } while ((arg = *++argv) != NULL);
6820 /* Now argv[0] is 1st argument */
6821
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006822 if (arg == NULL)
6823 return EXIT_SUCCESS;
6824 set_argv:
6825
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006826 /* NB: G.global_argv[0] ($0) is never freed/changed */
6827 g_argv = G.global_argv;
6828 if (G.global_args_malloced) {
6829 pp = g_argv;
6830 while (*++pp)
6831 free(*pp);
6832 g_argv[1] = NULL;
6833 } else {
6834 G.global_args_malloced = 1;
6835 pp = xzalloc(sizeof(pp[0]) * 2);
6836 pp[0] = g_argv[0]; /* retain $0 */
6837 g_argv = pp;
6838 }
6839 /* This realloc's G.global_argv */
6840 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6841
6842 n = 1;
6843 while (*++pp)
6844 n++;
6845 G.global_argc = n;
6846
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006847 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006848
6849 /* Nothing known, so abort */
6850 error:
6851 bb_error_msg("set: %s: invalid option", arg);
6852 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006853}
6854
6855static int builtin_shift(char **argv)
6856{
6857 int n = 1;
6858 if (argv[1]) {
6859 n = atoi(argv[1]);
6860 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006861 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006862 if (G.global_args_malloced) {
6863 int m = 1;
6864 while (m <= n)
6865 free(G.global_argv[m++]);
6866 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006867 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006868 memmove(&G.global_argv[1], &G.global_argv[n+1],
6869 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006870 return EXIT_SUCCESS;
6871 }
6872 return EXIT_FAILURE;
6873}
6874
6875static int builtin_source(char **argv)
6876{
6877 FILE *input;
Denis Vlasenko270b1c32009-04-17 18:54:50 +00006878 save_arg_t sv;
Mike Frysinger885b6f22009-04-18 21:04:25 +00006879#if ENABLE_HUSH_FUNCTIONS
6880 smallint sv_flg;
6881#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006882
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006883 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006884 return EXIT_FAILURE;
6885
Denis Vlasenko6b9e0532009-04-18 01:23:21 +00006886// TODO: search through $PATH is missing
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006887 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006888 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006889 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006890 return EXIT_FAILURE;
6891 }
6892 close_on_exec_on(fileno(input));
6893
Mike Frysinger885b6f22009-04-18 21:04:25 +00006894#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00006895 sv_flg = G.flag_return_in_progress;
6896 /* "we are inside sourced file, ok to use return" */
6897 G.flag_return_in_progress = -1;
Mike Frysinger885b6f22009-04-18 21:04:25 +00006898#endif
Denis Vlasenko270b1c32009-04-17 18:54:50 +00006899 save_and_replace_G_args(&sv, argv);
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00006900
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006901 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006902 fclose(input);
Denis Vlasenko270b1c32009-04-17 18:54:50 +00006903
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00006904 restore_G_args(&sv, argv);
Mike Frysinger885b6f22009-04-18 21:04:25 +00006905#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00006906 G.flag_return_in_progress = sv_flg;
Mike Frysinger885b6f22009-04-18 21:04:25 +00006907#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00006908
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006909 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006910}
6911
6912static int builtin_umask(char **argv)
6913{
Denis Vlasenkoeb858492009-04-18 02:06:54 +00006914 int rc;
6915 mode_t mask;
6916
6917 mask = umask(0);
6918 if (argv[1]) {
6919 mode_t old_mask = mask;
6920
6921 mask ^= 0777;
6922 rc = bb_parse_mode(argv[1], &mask);
6923 mask ^= 0777;
6924 if (rc == 0) {
6925 mask = old_mask;
6926 /* bash messages:
6927 * bash: umask: 'q': invalid symbolic mode operator
6928 * bash: umask: 999: octal number out of range
6929 */
6930 bb_error_msg("%s: '%s' invalid mode", argv[0], argv[1]);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006931 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006932 } else {
Denis Vlasenkoeb858492009-04-18 02:06:54 +00006933 rc = 1;
6934 /* Mimic bash */
6935 printf("%04o\n", (unsigned) mask);
6936 /* fall through and restore mask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006937 }
Denis Vlasenkoeb858492009-04-18 02:06:54 +00006938 umask(mask);
6939
6940 return !rc; /* rc != 0 - success */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006941}
6942
Mike Frysingerd690f682009-03-30 06:50:54 +00006943/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006944static int builtin_unset(char **argv)
6945{
Mike Frysingerd690f682009-03-30 06:50:54 +00006946 int ret;
Denis Vlasenko28e67962009-04-26 23:22:40 +00006947 unsigned opts;
Mike Frysingerd690f682009-03-30 06:50:54 +00006948
Denis Vlasenko28e67962009-04-26 23:22:40 +00006949 /* "!": do not abort on errors */
6950 /* "+": stop at 1st non-option */
6951 opts = getopt32(argv, "!+vf");
6952 if (opts == (unsigned)-1)
6953 return EXIT_FAILURE;
6954 if (opts == 3) {
6955 bb_error_msg("unset: -v and -f are exclusive");
6956 return EXIT_FAILURE;
Mike Frysingerd690f682009-03-30 06:50:54 +00006957 }
Denis Vlasenko28e67962009-04-26 23:22:40 +00006958 argv += optind;
Mike Frysingerd690f682009-03-30 06:50:54 +00006959
6960 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006961 while (*argv) {
Denis Vlasenko28e67962009-04-26 23:22:40 +00006962 if (!(opts & 2)) { /* not -f */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006963 if (unset_local_var(*argv)) {
6964 /* unset <nonexistent_var> doesn't fail.
6965 * Error is when one tries to unset RO var.
6966 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00006967 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006968 }
Mike Frysingerd690f682009-03-30 06:50:54 +00006969 }
Denis Vlasenko40e84372009-04-18 11:23:38 +00006970#if ENABLE_HUSH_FUNCTIONS
6971 else {
6972 unset_func(*argv);
6973 }
6974#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006975 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006976 }
6977 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006978}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006979
Mike Frysinger56bdea12009-03-28 20:01:58 +00006980/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6981static int builtin_wait(char **argv)
6982{
6983 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006984 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006985
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006986 if (*++argv == NULL) {
6987 /* Don't care about wait results */
6988 /* Note 1: must wait until there are no more children */
6989 /* Note 2: must be interruptible */
6990 /* Examples:
6991 * $ sleep 3 & sleep 6 & wait
6992 * [1] 30934 sleep 3
6993 * [2] 30935 sleep 6
6994 * [1] Done sleep 3
6995 * [2] Done sleep 6
6996 * $ sleep 3 & sleep 6 & wait
6997 * [1] 30936 sleep 3
6998 * [2] 30937 sleep 6
6999 * [1] Done sleep 3
7000 * ^C <-- after ~4 sec from keyboard
7001 * $
7002 */
7003 sigaddset(&G.blocked_set, SIGCHLD);
7004 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7005 while (1) {
7006 checkjobs(NULL);
7007 if (errno == ECHILD)
7008 break;
7009 /* Wait for SIGCHLD or any other signal of interest */
7010 /* sigtimedwait with infinite timeout: */
7011 sig = sigwaitinfo(&G.blocked_set, NULL);
7012 if (sig > 0) {
7013 sig = check_and_run_traps(sig);
7014 if (sig && sig != SIGCHLD) { /* see note 2 */
7015 ret = 128 + sig;
7016 break;
7017 }
7018 }
7019 }
7020 sigdelset(&G.blocked_set, SIGCHLD);
7021 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
7022 return ret;
7023 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00007024
Denis Vlasenko7566bae2009-03-31 17:24:49 +00007025 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00007026 while (*argv) {
7027 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00007028 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007029 /* mimic bash message */
7030 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007031 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00007032 }
7033 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00007034 if (WIFSIGNALED(status))
7035 ret = 128 + WTERMSIG(status);
7036 else if (WIFEXITED(status))
7037 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00007038 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00007039 ret = EXIT_FAILURE;
7040 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00007041 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00007042 ret = 127;
7043 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00007044 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00007045 }
7046
7047 return ret;
7048}
7049
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007050#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
7051static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
7052{
7053 if (argv[1]) {
7054 def = bb_strtou(argv[1], NULL, 10);
7055 if (errno || def < def_min || argv[2]) {
7056 bb_error_msg("%s: bad arguments", argv[0]);
7057 def = UINT_MAX;
7058 }
7059 }
7060 return def;
7061}
7062#endif
7063
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007064#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00007065static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007066{
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007067 unsigned depth;
Denis Vlasenko87a86552008-07-29 19:43:10 +00007068 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007069 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00007070 return EXIT_SUCCESS; /* bash compat */
7071 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00007072 G.flag_break_continue++; /* BC_BREAK = 1 */
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007073
7074 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
7075 if (depth == UINT_MAX)
7076 G.flag_break_continue = BC_BREAK;
7077 if (G.depth_of_loop < depth)
Denis Vlasenko87a86552008-07-29 19:43:10 +00007078 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007079
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007080 return EXIT_SUCCESS;
7081}
7082
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00007083static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007084{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00007085 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
7086 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00007087}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00007088#endif
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007089
7090#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenko7b9e5c52009-04-17 23:53:15 +00007091static int builtin_return(char **argv)
Denis Vlasenko3d40d8e2009-04-17 23:44:18 +00007092{
7093 int rc;
7094
7095 if (G.flag_return_in_progress != -1) {
7096 bb_error_msg("%s: not in a function or sourced script", argv[0]);
7097 return EXIT_FAILURE; /* bash compat */
7098 }
7099
7100 G.flag_return_in_progress = 1;
7101
7102 /* bash:
7103 * out of range: wraps around at 256, does not error out
7104 * non-numeric param:
7105 * f() { false; return qwe; }; f; echo $?
7106 * bash: return: qwe: numeric argument required <== we do this
7107 * 255 <== we also do this
7108 */
7109 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
7110 return rc;
7111}
7112#endif