blob: 04853137b1433758a71ce8ec11c8b15744cd9caa [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 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Denis Vlasenkoa8442002008-06-14 11:00:17 +000023 * o_addchr() derived from similar w_addchar function in glibc-2.2.
Eric Andersen25f27032001-04-26 23:22:31 +000024 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko424f79b2009-03-22 14:23:34 +000025 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000027 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
Mike Frysinger25a6ca02009-03-28 13:59:26 +000039 * POSIX syntax not implemented:
Eric Andersen78a7c992001-05-15 16:30:25 +000040 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000041 * <(list) and >(list) Process Substitution
Eric Andersen25f27032001-04-26 23:22:31 +000042 * Here Documents ( << word )
43 * Functions
Mike Frysinger25a6ca02009-03-28 13:59:26 +000044 * Tilde Expansion
Mike Frysinger6379bb42009-03-28 18:55:03 +000045 * Parameter Expansion for substring processing ${var#word} ${var%word}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000046 *
47 * Bash stuff maybe optional enable:
48 * &> and >& redirection of stdout+stderr
49 * Brace expansion
50 * reserved words: [[ ]] function select
Mike Frysinger6379bb42009-03-28 18:55:03 +000051 * substrings ${var:1:5}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000052 *
Eric Andersen25f27032001-04-26 23:22:31 +000053 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000054 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000055 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * port selected bugfixes from post-0.49 busybox lash - done?
Eric Andersen83a2ae22001-05-07 17:59:25 +000057 * change { and } from special chars to reserved words
Denis Vlasenkobcb25532008-07-28 23:04:34 +000058 * builtins: return, trap, ulimit
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +000059 * test magic exec with redirection only
Eric Andersen25f27032001-04-26 23:22:31 +000060 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000061 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000062 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
Eric Andersen25f27032001-04-26 23:22:31 +000064 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000065 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000066 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000067
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000068#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenko424f79b2009-03-22 14:23:34 +000069//TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
Denis Vlasenko61befda2008-11-25 01:36:03 +000070//#include "applet_tables.h" doesn't work
Denis Vlasenkobe709c22008-07-28 00:01:16 +000071#include <glob.h>
72/* #include <dmalloc.h> */
73#if ENABLE_HUSH_CASE
74#include <fnmatch.h>
75#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000076#include "math.h"
77
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +000078#ifdef WANT_TO_TEST_NOMMU
79# undef BB_MMU
80# undef USE_FOR_NOMMU
81# undef USE_FOR_MMU
82# define BB_MMU 0
83# define USE_FOR_NOMMU(...) __VA_ARGS__
84# define USE_FOR_MMU(...)
85#endif
86
Denis Vlasenko61befda2008-11-25 01:36:03 +000087#if defined SINGLE_APPLET_MAIN
88/* STANDALONE does not make sense, and won't compile */
89#undef CONFIG_FEATURE_SH_STANDALONE
90#undef ENABLE_FEATURE_SH_STANDALONE
91#undef USE_FEATURE_SH_STANDALONE
92#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
93#define ENABLE_FEATURE_SH_STANDALONE 0
94#define USE_FEATURE_SH_STANDALONE(...)
95#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
96#endif
97
Denis Vlasenko05743d72008-02-10 12:10:08 +000098#if !ENABLE_HUSH_INTERACTIVE
99#undef ENABLE_FEATURE_EDITING
100#define ENABLE_FEATURE_EDITING 0
101#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
102#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000103#endif
104
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000105/* Do we support ANY keywords? */
106#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
107#define HAS_KEYWORDS 1
108#define IF_HAS_KEYWORDS(...) __VA_ARGS__
109#define IF_HAS_NO_KEYWORDS(...)
110#else
111#define HAS_KEYWORDS 0
112#define IF_HAS_KEYWORDS(...)
113#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
114#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000115
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000116/* Keep unconditionally on for now */
117#define HUSH_DEBUG 1
118/* In progress... */
119#define ENABLE_HUSH_FUNCTIONS 0
120
121
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000122/* If you comment out one of these below, it will be #defined later
123 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000124#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000125/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000126#define debug_printf_parse(...) do {} while (0)
127#define debug_print_tree(a, b) do {} while (0)
128#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000129#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000130#define debug_printf_jobs(...) do {} while (0)
131#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000132#define debug_printf_glob(...) do {} while (0)
133#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000134#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000135#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000136
137#ifndef debug_printf
138#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000139#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000140
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000141#ifndef debug_printf_parse
142#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000143#endif
144
145#ifndef debug_printf_exec
146#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
147#endif
148
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000149#ifndef debug_printf_env
150#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
151#endif
152
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000153#ifndef debug_printf_jobs
154#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000155#define DEBUG_JOBS 1
156#else
157#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000158#endif
159
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000160#ifndef debug_printf_expand
161#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
162#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000163#else
164#define DEBUG_EXPAND 0
165#endif
166
167#ifndef debug_printf_glob
168#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
169#define DEBUG_GLOB 1
170#else
171#define DEBUG_GLOB 0
172#endif
173
174#ifndef debug_printf_list
175#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000176#endif
177
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000178#ifndef debug_printf_subst
179#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
180#endif
181
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000182#ifndef debug_printf_clean
183/* broken, of course, but OK for testing */
184static const char *indenter(int i)
185{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000186 static const char blanks[] ALIGN1 =
187 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000188 return &blanks[sizeof(blanks) - i - 1];
189}
190#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000191#define DEBUG_CLEAN 1
Denis Vlasenkoa0e65122009-04-05 23:39:14 +0000192#else
193#define DEBUG_CLEAN 0
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000194#endif
195
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000196#if DEBUG_EXPAND
197static void debug_print_strings(const char *prefix, char **vv)
198{
199 fprintf(stderr, "%s:\n", prefix);
200 while (*vv)
201 fprintf(stderr, " '%s'\n", *vv++);
202}
203#else
204#define debug_print_strings(prefix, vv) ((void)0)
205#endif
206
Denis Vlasenkof962a032007-11-23 12:50:54 +0000207/*
208 * Leak hunting. Use hush_leaktool.sh for post-processing.
209 */
210#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000211static void *xxmalloc(int lineno, size_t size)
Denis Vlasenkof962a032007-11-23 12:50:54 +0000212{
213 void *ptr = xmalloc((size + 0xff) & ~0xff);
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000214 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000215 return ptr;
216}
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000217static void *xxrealloc(int lineno, void *ptr, size_t size)
Denis Vlasenkof962a032007-11-23 12:50:54 +0000218{
219 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000220 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000221 return ptr;
222}
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000223static char *xxstrdup(int lineno, const char *str)
Denis Vlasenkof962a032007-11-23 12:50:54 +0000224{
225 char *ptr = xstrdup(str);
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000226 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000227 return ptr;
228}
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000229static void xxfree(void *ptr)
Denis Vlasenkof962a032007-11-23 12:50:54 +0000230{
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000231 fdprintf(2, "free %p\n", ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000232 free(ptr);
233}
234#define xmalloc(s) xxmalloc(__LINE__, s)
235#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
236#define xstrdup(s) xxstrdup(__LINE__, s)
237#define free(p) xxfree(p)
238#endif
239
240
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000241#define ERR_PTR ((void*)(long)1)
242
Mike Frysinger258275d2009-04-05 21:19:43 +0000243static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000244
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000245#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000246
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000247#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000248
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000249typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000250 REDIRECT_INPUT = 1,
251 REDIRECT_OVERWRITE = 2,
252 REDIRECT_APPEND = 3,
253 REDIRECT_HEREIS = 4,
254 REDIRECT_IO = 5
255} redir_type;
256
Denis Vlasenko55789c62008-06-18 16:30:42 +0000257/* The descrip member of this structure is only used to make
258 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000259static const struct {
260 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000261 signed char default_fd;
262 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000263} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000264 { 0, 0, "()" },
265 { O_RDONLY, 0, "<" },
266 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
267 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
268 { O_RDONLY, -1, "<<" },
269 { O_RDWR, 1, "<>" }
270};
271
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000272typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000273 PIPE_SEQ = 1,
274 PIPE_AND = 2,
275 PIPE_OR = 3,
276 PIPE_BG = 4,
277} pipe_style;
278
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000279typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000280 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000281#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000282 RES_IF ,
283 RES_THEN ,
284 RES_ELIF ,
285 RES_ELSE ,
286 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000287#endif
288#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000289 RES_FOR ,
290 RES_WHILE ,
291 RES_UNTIL ,
292 RES_DO ,
293 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000294#endif
295#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000296 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000297#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000298#if ENABLE_HUSH_CASE
299 RES_CASE ,
300 /* two pseudo-keywords support contrived "case" syntax: */
301 RES_MATCH , /* "word)" */
302 RES_CASEI , /* "this command is inside CASE" */
303 RES_ESAC ,
304#endif
305 RES_XXXX ,
306 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000307} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000308
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000309typedef struct o_string {
310 char *data;
311 int length; /* position where data is appended */
312 int maxlen;
313 /* Protect newly added chars against globbing
314 * (by prepending \ to *, ?, [, \) */
315 smallint o_escape;
316 smallint o_glob;
317 smallint nonnull;
318 smallint has_empty_slot;
319 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
320} o_string;
321enum {
322 MAYBE_ASSIGNMENT = 0,
323 DEFINITELY_ASSIGNMENT = 1,
324 NOT_ASSIGNMENT = 2,
325 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
326};
327/* Used for initialization: o_string foo = NULL_O_STRING; */
328#define NULL_O_STRING { NULL }
329
330/* I can almost use ordinary FILE*. Is open_memstream() universally
331 * available? Where is it documented? */
332typedef struct in_str {
333 const char *p;
334 /* eof_flag=1: last char in ->p is really an EOF */
335 char eof_flag; /* meaningless if ->p == NULL */
336 char peek_buf[2];
337#if ENABLE_HUSH_INTERACTIVE
338 smallint promptme;
339 smallint promptmode; /* 0: PS1, 1: PS2 */
340#endif
341 FILE *file;
342 int (*get) (struct in_str *);
343 int (*peek) (struct in_str *);
344} in_str;
345#define i_getch(input) ((input)->get(input))
346#define i_peek(input) ((input)->peek(input))
347
Eric Andersen25f27032001-04-26 23:22:31 +0000348struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000349 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000350 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000351 int fd; /* file descriptor being redirected */
352 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000353 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000354};
355
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000356struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000357 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000358 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000359 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000360 smallint grp_type; /* GRP_xxx */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000361 struct pipe *group; /* if non-NULL, this "command" is { list },
362 * ( list ), or a compound statement */
363#if !BB_MMU
364 char *group_as_string;
365#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000366 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000367 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000368};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000369/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
370 * and on execution these are substituted with their values.
371 * Substitution can make _several_ words out of one argv[n]!
372 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000373 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000374 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000375#define GRP_NORMAL 0
376#define GRP_SUBSHELL 1
377#if ENABLE_HUSH_FUNCTIONS
378#define GRP_FUNCTION 2
379#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000380
381struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000382 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000383 int num_cmds; /* total number of commands in job */
384 int alive_cmds; /* number of commands running (not exited) */
385 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000386#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000387 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000388 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000389 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000390#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000391 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000392 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000393 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
394 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000395};
396
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000397/* This holds pointers to the various results of parsing */
398struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000399 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000400 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000401 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000402 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000403 /* last command in pipe (being constructed right now) */
404 struct command *command;
405 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000406 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000407#if !BB_MMU
408 o_string as_string;
409#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000410#if HAS_KEYWORDS
411 smallint ctx_res_w;
412 smallint ctx_inverted; /* "! cmd | cmd" */
413#if ENABLE_HUSH_CASE
414 smallint ctx_dsemicolon; /* ";;" seen */
415#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000416 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
417 int old_flag;
418 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000419 * example: "if pipe1; pipe2; then pipe3; fi"
420 * when we see "if" or "then", we malloc and copy current context,
421 * and make ->stack point to it. then we parse pipeN.
422 * when closing "then" / fi" / whatever is found,
423 * we move list_head into ->stack->command->group,
424 * copy ->stack into current context, and delete ->stack.
425 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000426 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000427 struct parse_context *stack;
428#endif
429};
430
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000431/* On program start, environ points to initial environment.
432 * putenv adds new pointers into it, unsetenv removes them.
433 * Neither of these (de)allocates the strings.
434 * setenv allocates new strings in malloc space and does putenv,
435 * and thus setenv is unusable (leaky) for shell's purposes */
436#define setenv(...) setenv_is_leaky_dont_use()
437struct variable {
438 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000439 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000440 int max_len; /* if > 0, name is part of initial env; else name is malloced */
441 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000442 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000443};
444
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000445enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000446 BC_BREAK = 1,
447 BC_CONTINUE = 2,
448};
449
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000450
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000451/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000452/* Sorted roughly by size (smaller offsets == smaller code) */
453struct globals {
454#if ENABLE_HUSH_INTERACTIVE
455 /* 'interactive_fd' is a fd# open to ctty, if we have one
456 * _AND_ if we decided to act interactively */
457 int interactive_fd;
458 const char *PS1;
459 const char *PS2;
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000460#define G_interactive_fd (G.interactive_fd)
461#else
462#define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000463#endif
464#if ENABLE_FEATURE_EDITING
465 line_input_t *line_input_state;
466#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000467 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000468 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000469#if ENABLE_HUSH_JOB
470 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000471 pid_t saved_tty_pgrp;
472 int last_jobid;
473 struct pipe *job_list;
474 struct pipe *toplevel_list;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000475//// smallint ctrl_z_flag;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000476#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000477 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000478#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000479 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000480#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481 smallint fake_mode;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000482 /* These four support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000483 smalluint last_return_code;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000484 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000485 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000486 /* how many non-NULL argv's we have. NB: $# + 1 */
487 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000488 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000489#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000490 char *argv0_for_re_execing;
491 char **argv_from_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000492#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000493#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000494 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000495 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000496#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000497 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000498 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000499 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000500 struct variable shell_ver;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000501 /* Signal and trap handling */
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000502// unsigned count_SIGCHLD;
503// unsigned handled_SIGCHLD;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000504 /* which signals have non-DFL handler (even with no traps set)? */
505 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000506 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000507 sigset_t blocked_set;
508 sigset_t inherited_set;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000509 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
510#if ENABLE_FEATURE_SH_STANDALONE
511 struct nofork_save_area nofork_save;
512#endif
513#if ENABLE_HUSH_JOB
514 sigjmp_buf toplevel_jb;
515#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000516};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000517#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000518/* Not #defining name to G.name - this quickly gets unwieldy
519 * (too many defines). Also, I actually prefer to see when a variable
520 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000521#define INIT_G() do { \
522 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
523} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000524
525
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000526/* Function prototypes for builtins */
527static int builtin_cd(char **argv);
528static int builtin_echo(char **argv);
529static int builtin_eval(char **argv);
530static int builtin_exec(char **argv);
531static int builtin_exit(char **argv);
532static int builtin_export(char **argv);
533#if ENABLE_HUSH_JOB
534static int builtin_fg_bg(char **argv);
535static int builtin_jobs(char **argv);
536#endif
537#if ENABLE_HUSH_HELP
538static int builtin_help(char **argv);
539#endif
540static int builtin_pwd(char **argv);
541static int builtin_read(char **argv);
542static int builtin_test(char **argv);
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000543static int builtin_trap(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000544static int builtin_true(char **argv);
545static int builtin_set(char **argv);
546static int builtin_shift(char **argv);
547static int builtin_source(char **argv);
548static int builtin_umask(char **argv);
549static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000550static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000551#if ENABLE_HUSH_LOOPS
552static int builtin_break(char **argv);
553static int builtin_continue(char **argv);
554#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000555
556/* Table of built-in functions. They can be forked or not, depending on
557 * context: within pipes, they fork. As simple commands, they do not.
558 * When used in non-forking context, they can change global variables
559 * in the parent shell process. If forked, of course they cannot.
560 * For example, 'unset foo | whatever' will parse and run, but foo will
561 * still be set at the end. */
562struct built_in_command {
563 const char *cmd;
564 int (*function)(char **argv);
565#if ENABLE_HUSH_HELP
566 const char *descr;
567#define BLTIN(cmd, func, help) { cmd, func, help }
568#else
569#define BLTIN(cmd, func, help) { cmd, func }
570#endif
571};
572
573/* For now, echo and test are unconditionally enabled.
574 * Maybe make it configurable? */
575static const struct built_in_command bltins[] = {
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000576 BLTIN("." , builtin_source , "Run commands in a file"),
577 BLTIN(":" , builtin_true , "No-op"),
578 BLTIN("[" , builtin_test , "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000579#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000580 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000581#endif
582#if ENABLE_HUSH_LOOPS
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000583 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000584#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000585 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000586#if ENABLE_HUSH_LOOPS
587 BLTIN("continue", builtin_continue, "Start new loop iteration"),
588#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000589 BLTIN("echo" , builtin_echo , "Write to stdout"),
590 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
591 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
592 BLTIN("exit" , builtin_exit , "Exit"),
593 BLTIN("export" , builtin_export , "Set environment variable"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000594#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000595 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000596#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000597#if ENABLE_HUSH_HELP
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000598 BLTIN("help" , builtin_help , "List shell built-in commands"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000599#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000600#if ENABLE_HUSH_JOB
601 BLTIN("jobs" , builtin_jobs , "List active jobs"),
602#endif
603 BLTIN("pwd" , builtin_pwd , "Print current directory"),
604 BLTIN("read" , builtin_read , "Input environment variable"),
605// BLTIN("return" , builtin_return , "Return from a function"),
606 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
607 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
608 BLTIN("test" , builtin_test , "Test condition"),
609 BLTIN("trap" , builtin_trap , "Trap signals"),
610// BLTIN("ulimit" , builtin_return , "Control resource limits"),
611 BLTIN("umask" , builtin_umask , "Set file creation mask"),
612 BLTIN("unset" , builtin_unset , "Unset environment variable"),
613 BLTIN("wait" , builtin_wait , "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000614};
615
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000616
Mike Frysinger6379bb42009-03-28 18:55:03 +0000617static void maybe_die(const char *notice, const char *msg)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000618{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000619 /* Was using fancy stuff:
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000620 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000621 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000622 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
623#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerdfa9de72009-04-03 22:48:10 +0000624 if (G_interactive_fd)
625 fp = bb_error_msg;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000626#endif
Mike Frysinger6379bb42009-03-28 18:55:03 +0000627 fp(msg ? "%s: %s" : notice, notice, msg);
628}
Mike Frysinger5a828452009-03-28 19:09:04 +0000629#if 1
630#define syntax(msg) maybe_die("syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000631#else
Mike Frysinger5a828452009-03-28 19:09:04 +0000632/* Debug -- trick gcc to expand __LINE__ and convert to string */
633#define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
634#define _syntax(msg, line) __syntax(msg, line)
635#define syntax(msg) _syntax(msg, __LINE__)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000636#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000637
Denis Vlasenko552433b2009-04-04 19:29:21 +0000638
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000639static int glob_needed(const char *s)
640{
641 while (*s) {
642 if (*s == '\\')
643 s++;
644 if (*s == '*' || *s == '[' || *s == '?')
645 return 1;
646 s++;
647 }
648 return 0;
649}
650
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000651static int is_assignment(const char *s)
652{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000653 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000654 return 0;
655 s++;
656 while (isalnum(*s) || *s == '_')
657 s++;
658 return *s == '=';
659}
660
Denis Vlasenko55789c62008-06-18 16:30:42 +0000661/* Replace each \x with x in place, return ptr past NUL. */
662static char *unbackslash(char *src)
663{
664 char *dst = src;
665 while (1) {
666 if (*src == '\\')
667 src++;
668 if ((*dst++ = *src++) == '\0')
669 break;
670 }
671 return dst;
672}
673
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000674static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000675{
676 int i;
677 unsigned count1;
678 unsigned count2;
679 char **v;
680
681 v = strings;
682 count1 = 0;
683 if (v) {
684 while (*v) {
685 count1++;
686 v++;
687 }
688 }
689 count2 = 0;
690 v = add;
691 while (*v) {
692 count2++;
693 v++;
694 }
695 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
696 v[count1 + count2] = NULL;
697 i = count2;
698 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000699 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000700 return v;
701}
702
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000703static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000704{
705 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000706 v[0] = add;
707 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000708 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000709}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000710
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000711static void putenv_all(char **strings)
712{
713 if (!strings)
714 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000715 while (*strings) {
716 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000717 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000718 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000719}
720
721static char **putenv_all_and_save_old(char **strings)
722{
723 char **old = NULL;
724 char **s = strings;
725
726 if (!strings)
727 return old;
728 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000729 char *v, *eq;
730
731 eq = strchr(*strings, '=');
732 if (eq) {
733 *eq = '\0';
734 v = getenv(*strings);
735 *eq = '=';
736 if (v) {
737 /* v points to VAL in VAR=VAL, go back to VAR */
738 v -= (eq - *strings) + 1;
739 old = add_string_to_strings(old, v);
740 }
741 }
742 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000743 }
744 putenv_all(s);
745 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000746}
747
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000748static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000749{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000750 char **v;
751
752 if (!strings)
753 return;
754
755 v = strings;
756 while (*v) {
757 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000758 debug_printf_env("unsetenv '%s'\n", *v);
759 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000760 }
761 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000762 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000763 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000764}
765
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000766static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000767{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000768 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000769}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000770
771
Denis Vlasenkod5762932009-03-31 11:22:57 +0000772/* Basic theory of signal handling in shell
773 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000774 * This does not describe what hush does, rather, it is current understanding
775 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000776 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
777 *
778 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
779 * is finished or backgrounded. It is the same in interactive and
780 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000781 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000782 * ^C or ^Z from keyboard seem to execute "at once" because it usually
783 * backgrounds (i.e. stops) or kills all members of currently running
784 * pipe.
785 *
786 * Wait builtin in interruptible by signals for which user trap is set
787 * or by SIGINT in interactive shell.
788 *
789 * Trap handlers will execute even within trap handlers. (right?)
790 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000791 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
Denis Vlasenkod5762932009-03-31 11:22:57 +0000792 *
793 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000794 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000795 *
796 * Commands run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000797 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000798 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000799 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
800 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000801 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000802 * Siganls which differ from SIG_DFL action
803 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +0000804 *
805 * SIGQUIT: ignore
806 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000807 * SIGHUP (interactive):
808 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +0000809 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000810 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
811 * that all pipe members are stopped) (right?)
Denis Vlasenkod5762932009-03-31 11:22:57 +0000812 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000813 * of the command line, show prompt. NB: ^C does not send SIGINT
814 * to interactive shell while shell is waiting for a pipe,
815 * since shell is bg'ed (is not in foreground process group).
816 * (check/expand this)
817 * Example 1: this waits 5 sec, but does not execute ls:
818 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
819 * Example 2: this does not wait and does not execute ls:
820 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
821 * Example 3: this does not wait 5 sec, but executes ls:
822 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +0000823 *
824 * (What happens to signals which are IGN on shell start?)
825 * (What happens with signal mask on shell start?)
826 *
827 * Implementation in hush
828 * ======================
829 * We use in-kernel pending signal mask to determine which signals were sent.
830 * We block all signals which we don't want to take action immediately,
831 * i.e. we block all signals which need to have special handling as described
832 * above, and all signals which have traps set.
833 * After each pipe execution, we extract any pending signals via sigtimedwait()
834 * and act on them.
835 *
836 * unsigned non_DFL_mask: a mask of such "special" signals
837 * sigset_t blocked_set: current blocked signal set
838 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000839 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +0000840 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000841 * "trap 'cmd' SIGxxx":
842 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +0000843 * after [v]fork, if we plan to be a shell:
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000844 * nothing for {} child shell (say, "true | { true; true; } | true")
845 * unset all traps if () shell. [TODO]
Denis Vlasenkod5762932009-03-31 11:22:57 +0000846 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000847 * POSIX says pending signal mask is cleared in child - no need to clear it.
848 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000849 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000850 * Note: as a result, we do not use signal handlers much. The only uses
851 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
852 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000853 */
854
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000855//static void SIGCHLD_handler(int sig UNUSED_PARAM)
856//{
857// G.count_SIGCHLD++;
858//}
859
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000860static int check_and_run_traps(int sig)
Denis Vlasenkod5762932009-03-31 11:22:57 +0000861{
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000862 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenkod5762932009-03-31 11:22:57 +0000863 smalluint save_rcode;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000864 int last_sig = 0;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000865
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000866 if (sig)
867 goto jump_in;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000868 while (1) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000869 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
Denis Vlasenkod5762932009-03-31 11:22:57 +0000870 if (sig <= 0)
871 break;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000872 jump_in:
873 last_sig = sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000874 if (G.traps && G.traps[sig]) {
875 if (G.traps[sig][0]) {
876 /* We have user-defined handler */
877 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
878 save_rcode = G.last_return_code;
879 builtin_eval(argv);
880 free(argv[1]);
881 G.last_return_code = save_rcode;
882 } /* else: "" trap, ignoring signal */
883 continue;
884 }
885 /* not a trap: special action */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000886 switch (sig) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000887// case SIGCHLD:
888// G.count_SIGCHLD++;
889// break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000890 case SIGINT:
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000891 bb_putchar('\n');
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000892 G.flag_SIGINT = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000893 break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000894//TODO
895// case SIGHUP: ...
896// break;
Denis Vlasenkod3f973e2009-04-06 10:21:42 +0000897 default: /* ignored: */
898 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000899 break;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000900 }
Denis Vlasenkod5762932009-03-31 11:22:57 +0000901 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000902 return last_sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000903}
904
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000905#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000906/* Restores tty foreground process group, and exits.
907 * May be called as signal handler for fatal signal
908 * (will faithfully resend signal to itself, producing correct exit state)
909 * or called directly with -EXITCODE.
910 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000911static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000912static void sigexit(int sig)
913{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000914 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000915 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000916
Denis Vlasenkoabedaac2009-03-31 12:03:40 +0000917 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000918 * tty pgrp then, only top-level shell process does that */
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000919 if (G_interactive_fd && getpid() == G.root_pid)
920 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000921
922 /* Not a signal, just exit */
923 if (sig <= 0)
924 _exit(- sig);
925
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000926 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000927}
Denis Vlasenkoe0755e52009-04-03 21:16:45 +0000928#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000929
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000930/* Restores tty foreground process group, and exits. */
931static void hush_exit(int exitcode) NORETURN;
932static void hush_exit(int exitcode)
933{
Denis Vlasenkod5762932009-03-31 11:22:57 +0000934 if (G.traps && G.traps[0] && G.traps[0][0]) {
935 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
Denis Vlasenkof9375282009-04-05 19:13:39 +0000936//TODO: do we need to prevent recursion?
Denis Vlasenkod5762932009-03-31 11:22:57 +0000937 builtin_eval(argv);
938 free(argv[1]);
939 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000940
Denis Vlasenkoabedaac2009-03-31 12:03:40 +0000941#if ENABLE_HUSH_JOB
942 fflush(NULL); /* flush all streams */
943 sigexit(- (exitcode & 0xff));
944#else
945 exit(exitcode);
946#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000947}
948
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000949
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000950static const char *set_cwd(void)
951{
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000952 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
953 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000954 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000955 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000956 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
957 if (!G.cwd)
958 G.cwd = bb_msg_unknown;
959 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000960}
961
Denis Vlasenko83506862007-11-23 13:11:42 +0000962
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000963/* Get/check local shell variables */
964static struct variable *get_local_var(const char *name)
965{
966 struct variable *cur;
967 int len;
968
969 if (!name)
970 return NULL;
971 len = strlen(name);
972 for (cur = G.top_var; cur; cur = cur->next) {
973 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
974 return cur;
975 }
976 return NULL;
977}
978
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000979static const char *get_local_var_value(const char *src)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000980{
981 struct variable *var = get_local_var(src);
982 if (var)
983 return strchr(var->varstr, '=') + 1;
984 return NULL;
985}
986
987/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +0000988 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +0000989 * flg_export:
Mike Frysinger6379bb42009-03-28 18:55:03 +0000990 * 0: do not export
991 * 1: export
992 * -1: if NAME is set, leave export status alone
993 * if NAME is not set, do not export
Denis Vlasenko0bb4a232009-04-05 01:42:59 +0000994 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +0000995 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +0000996#if BB_MMU
997#define set_local_var(str, flg_export, flg_read_only) \
998 set_local_var(str, flg_export)
999#endif
1000static int set_local_var(char *str, int flg_export, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001001{
1002 struct variable *cur;
1003 char *value;
1004 int name_len;
1005
1006 value = strchr(str, '=');
1007 if (!value) { /* not expected to ever happen? */
1008 free(str);
1009 return -1;
1010 }
1011
1012 name_len = value - str + 1; /* including '=' */
1013 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1014 while (1) {
1015 if (strncmp(cur->varstr, str, name_len) != 0) {
1016 if (!cur->next) {
1017 /* Bail out. Note that now cur points
1018 * to last var in linked list */
1019 break;
1020 }
1021 cur = cur->next;
1022 continue;
1023 }
1024 /* We found an existing var with this name */
1025 *value = '\0';
1026 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001027#if !BB_MMU
1028 if (!flg_read_only)
1029#endif
1030 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001031 free(str);
1032 return -1;
1033 }
1034 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1035 unsetenv(str); /* just in case */
1036 *value = '=';
1037 if (strcmp(cur->varstr, str) == 0) {
1038 free_and_exp:
1039 free(str);
1040 goto exp;
1041 }
1042 if (cur->max_len >= strlen(str)) {
1043 /* This one is from startup env, reuse space */
1044 strcpy(cur->varstr, str);
1045 goto free_and_exp;
1046 }
1047 /* max_len == 0 signifies "malloced" var, which we can
1048 * (and has to) free */
1049 if (!cur->max_len)
1050 free(cur->varstr);
1051 cur->max_len = 0;
1052 goto set_str_and_exp;
1053 }
1054
1055 /* Not found - create next variable struct */
1056 cur->next = xzalloc(sizeof(*cur));
1057 cur = cur->next;
1058
1059 set_str_and_exp:
1060 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001061#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001062 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001063#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001064 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001065 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001066 cur->flg_export = 1;
1067 if (cur->flg_export) {
1068 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1069 return putenv(cur->varstr);
1070 }
1071 return 0;
1072}
1073
Mike Frysingerd690f682009-03-30 06:50:54 +00001074static int unset_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001075{
1076 struct variable *cur;
1077 struct variable *prev = prev; /* for gcc */
1078 int name_len;
1079
1080 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001081 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001082 name_len = strlen(name);
1083 cur = G.top_var;
1084 while (cur) {
1085 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1086 if (cur->flg_read_only) {
1087 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001088 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001089 }
1090 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1091 * is ro, and we cannot reach this code on the 1st pass */
1092 prev->next = cur->next;
1093 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1094 bb_unsetenv(cur->varstr);
1095 if (!cur->max_len)
1096 free(cur->varstr);
1097 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001098 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001099 }
1100 prev = cur;
1101 cur = cur->next;
1102 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001103 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001104}
1105
Mike Frysinger98c52642009-04-02 10:02:37 +00001106#if ENABLE_SH_MATH_SUPPORT
1107#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1108#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1109static char *endofname(const char *name)
1110{
1111 char *p;
1112
1113 p = (char *) name;
1114 if (!is_name(*p))
1115 return p;
1116 while (*++p) {
1117 if (!is_in_name(*p))
1118 break;
1119 }
1120 return p;
1121}
1122
1123static void arith_set_local_var(const char *name, const char *val, int flags)
1124{
1125 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001126 char *var = xasprintf("%s=%s", name, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001127 set_local_var(var, flags, 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001128}
1129#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001130
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001131
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001132/*
1133 * in_str support
1134 */
1135static int static_get(struct in_str *i)
1136{
1137 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001138 if (ch != '\0')
1139 return ch;
1140 i->p--;
1141 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001142}
1143
1144static int static_peek(struct in_str *i)
1145{
1146 return *i->p;
1147}
1148
1149#if ENABLE_HUSH_INTERACTIVE
1150
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001151static void cmdedit_set_initial_prompt(void)
1152{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001153 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1154 G.PS1 = getenv("PS1");
1155 if (G.PS1 == NULL)
1156 G.PS1 = "\\w \\$ ";
1157 } else
1158 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001159}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001160
1161static const char* setup_prompt_string(int promptmode)
1162{
1163 const char *prompt_str;
1164 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001165 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1166 /* Set up the prompt */
1167 if (promptmode == 0) { /* PS1 */
1168 free((char*)G.PS1);
1169 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1170 prompt_str = G.PS1;
1171 } else
1172 prompt_str = G.PS2;
1173 } else
1174 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001175 debug_printf("result '%s'\n", prompt_str);
1176 return prompt_str;
1177}
1178
1179static void get_user_input(struct in_str *i)
1180{
1181 int r;
1182 const char *prompt_str;
1183
1184 prompt_str = setup_prompt_string(i->promptmode);
1185#if ENABLE_FEATURE_EDITING
1186 /* Enable command line editing only while a command line
1187 * is actually being read */
1188 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001189 G.flag_SIGINT = 0;
1190 /* buglet: SIGINT will not make new prompt to appear _at once_,
1191 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001192 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001193 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001194 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001195 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001196 i->eof_flag = (r < 0);
1197 if (i->eof_flag) { /* EOF/error detected */
1198 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1199 G.user_input_buf[1] = '\0';
1200 }
1201#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001202 do {
1203 G.flag_SIGINT = 0;
1204 fputs(prompt_str, stdout);
1205 fflush(stdout);
1206 G.user_input_buf[0] = r = fgetc(i->file);
1207 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001208//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001209 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001210 i->eof_flag = (r == EOF);
1211#endif
1212 i->p = G.user_input_buf;
1213}
1214
1215#endif /* INTERACTIVE */
1216
1217/* This is the magic location that prints prompts
1218 * and gets data back from the user */
1219static int file_get(struct in_str *i)
1220{
1221 int ch;
1222
1223 /* If there is data waiting, eat it up */
1224 if (i->p && *i->p) {
1225#if ENABLE_HUSH_INTERACTIVE
1226 take_cached:
1227#endif
1228 ch = *i->p++;
1229 if (i->eof_flag && !*i->p)
1230 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001231 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001232 } else {
1233 /* need to double check i->file because we might be doing something
1234 * more complicated by now, like sourcing or substituting. */
1235#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001236 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001237 do {
1238 get_user_input(i);
1239 } while (!*i->p); /* need non-empty line */
1240 i->promptmode = 1; /* PS2 */
1241 i->promptme = 0;
1242 goto take_cached;
1243 }
1244#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001245 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001246 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001247 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001248#if ENABLE_HUSH_INTERACTIVE
1249 if (ch == '\n')
1250 i->promptme = 1;
1251#endif
1252 return ch;
1253}
1254
Denis Vlasenko913a2012009-04-05 22:17:04 +00001255/* All callers guarantee this routine will never
1256 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001257 */
1258static int file_peek(struct in_str *i)
1259{
1260 int ch;
1261 if (i->p && *i->p) {
1262 if (i->eof_flag && !i->p[1])
1263 return EOF;
1264 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001265 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001266 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001267 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001268 i->eof_flag = (ch == EOF);
1269 i->peek_buf[0] = ch;
1270 i->peek_buf[1] = '\0';
1271 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001272 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001273 return ch;
1274}
1275
1276static void setup_file_in_str(struct in_str *i, FILE *f)
1277{
1278 i->peek = file_peek;
1279 i->get = file_get;
1280#if ENABLE_HUSH_INTERACTIVE
1281 i->promptme = 1;
1282 i->promptmode = 0; /* PS1 */
1283#endif
1284 i->file = f;
1285 i->p = NULL;
1286}
1287
1288static void setup_string_in_str(struct in_str *i, const char *s)
1289{
1290 i->peek = static_peek;
1291 i->get = static_get;
1292#if ENABLE_HUSH_INTERACTIVE
1293 i->promptme = 1;
1294 i->promptmode = 0; /* PS1 */
1295#endif
1296 i->p = s;
1297 i->eof_flag = 0;
1298}
1299
1300
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001301/*
1302 * o_string support
1303 */
1304#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001305
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001306static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001307{
1308 o->length = 0;
1309 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001310 if (o->data)
1311 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001312}
1313
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001314static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001315{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001316 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001317 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001318}
1319
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001320static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1321{
1322 free(o->data);
1323}
1324
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001325static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001326{
1327 if (o->length + len > o->maxlen) {
1328 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1329 o->data = xrealloc(o->data, 1 + o->maxlen);
1330 }
1331}
1332
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001333static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001334{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001335 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1336 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001337 o->data[o->length] = ch;
1338 o->length++;
1339 o->data[o->length] = '\0';
1340}
1341
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001342static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001343{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001344 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001345 memcpy(&o->data[o->length], str, len);
1346 o->length += len;
1347 o->data[o->length] = '\0';
1348}
1349
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001350#if !BB_MMU
1351static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001352{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001353 o_addblock(o, str, strlen(str));
1354}
1355#endif
1356
1357static void o_addstr_with_NUL(o_string *o, const char *str)
1358{
1359 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001360}
1361
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001362static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001363{
1364 while (len) {
1365 o_addchr(o, *str);
1366 if (*str++ == '\\'
1367 && (*str != '*' && *str != '?' && *str != '[')
1368 ) {
1369 o_addchr(o, '\\');
1370 }
1371 len--;
1372 }
1373}
1374
Eric Andersen25f27032001-04-26 23:22:31 +00001375/* My analysis of quoting semantics tells me that state information
1376 * is associated with a destination, not a source.
1377 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001378static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001379{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001380 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001381 char *found = strchr("*?[\\", ch);
1382 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001383 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001384 o_grow_by(o, sz);
1385 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001386 o->data[o->length] = '\\';
1387 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001388 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001389 o->data[o->length] = ch;
1390 o->length++;
1391 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001392}
1393
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001394static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001395{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001396 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001397 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001398 sz++;
1399 o->data[o->length] = '\\';
1400 o->length++;
1401 }
1402 o_grow_by(o, sz);
1403 o->data[o->length] = ch;
1404 o->length++;
1405 o->data[o->length] = '\0';
1406}
1407
1408static void o_addQstr(o_string *o, const char *str, int len)
1409{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001410 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001411 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001412 return;
1413 }
1414 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001415 char ch;
1416 int sz;
1417 int ordinary_cnt = strcspn(str, "*?[\\");
1418 if (ordinary_cnt > len) /* paranoia */
1419 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001420 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001421 if (ordinary_cnt == len)
1422 return;
1423 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001424 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001425
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001426 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001427 sz = 1;
1428 if (ch) { /* it is necessarily one of "*?[\\" */
1429 sz++;
1430 o->data[o->length] = '\\';
1431 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001432 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001433 o_grow_by(o, sz);
1434 o->data[o->length] = ch;
1435 o->length++;
1436 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001437 }
1438}
1439
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001440/* A special kind of o_string for $VAR and `cmd` expansion.
1441 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001442 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001443 * list[i] contains an INDEX (int!) into this string data.
1444 * It means that if list[] needs to grow, data needs to be moved higher up
1445 * but list[i]'s need not be modified.
1446 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001447 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001448 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1449 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001450#if DEBUG_EXPAND || DEBUG_GLOB
1451static void debug_print_list(const char *prefix, o_string *o, int n)
1452{
1453 char **list = (char**)o->data;
1454 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1455 int i = 0;
1456 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1457 prefix, list, n, string_start, o->length, o->maxlen);
1458 while (i < n) {
1459 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1460 o->data + (int)list[i] + string_start,
1461 o->data + (int)list[i] + string_start);
1462 i++;
1463 }
1464 if (n) {
1465 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001466 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001467 }
1468}
1469#else
1470#define debug_print_list(prefix, o, n) ((void)0)
1471#endif
1472
1473/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1474 * in list[n] so that it points past last stored byte so far.
1475 * It returns n+1. */
1476static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001477{
1478 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001479 int string_start;
1480 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001481
1482 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001483 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1484 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001485 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001486 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001487 /* list[n] points to string_start, make space for 16 more pointers */
1488 o->maxlen += 0x10 * sizeof(list[0]);
1489 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001490 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001491 memmove(list + n + 0x10, list + n, string_len);
1492 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001493 } else {
1494 debug_printf_list("list[%d]=%d string_start=%d\n",
1495 n, string_len, string_start);
1496 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001497 } else {
1498 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001499 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1500 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001501 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1502 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001503 o->has_empty_slot = 0;
1504 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001505 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001506 return n + 1;
1507}
1508
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001509/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001510static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001511{
1512 char **list = (char**)o->data;
1513 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1514
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001515 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001516}
1517
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001518/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001519 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001520static int o_glob(o_string *o, int n)
1521{
1522 glob_t globdata;
1523 int gr;
1524 char *pattern;
1525
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001526 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001527 if (!o->data)
1528 return o_save_ptr_helper(o, n);
1529 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001530 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001531 if (!glob_needed(pattern)) {
1532 literal:
1533 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001534 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001535 return o_save_ptr_helper(o, n);
1536 }
1537
1538 memset(&globdata, 0, sizeof(globdata));
1539 gr = glob(pattern, 0, NULL, &globdata);
1540 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1541 if (gr == GLOB_NOSPACE)
1542 bb_error_msg_and_die("out of memory during glob");
1543 if (gr == GLOB_NOMATCH) {
1544 globfree(&globdata);
1545 goto literal;
1546 }
1547 if (gr != 0) { /* GLOB_ABORTED ? */
1548//TODO: testcase for bad glob pattern behavior
1549 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1550 }
1551 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1552 char **argv = globdata.gl_pathv;
1553 o->length = pattern - o->data; /* "forget" pattern */
1554 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001555 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001556 n = o_save_ptr_helper(o, n);
1557 argv++;
1558 if (!*argv)
1559 break;
1560 }
1561 }
1562 globfree(&globdata);
1563 if (DEBUG_GLOB)
1564 debug_print_list("o_glob returning", o, n);
1565 return n;
1566}
1567
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001568/* If o->o_glob == 1, glob the string so far remembered.
1569 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001570static int o_save_ptr(o_string *o, int n)
1571{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001572 if (o->o_glob) { /* if globbing is requested */
1573 /* If o->has_empty_slot, list[n] was already globbed
1574 * (if it was requested back then when it was filled)
1575 * so don't do that again! */
1576 if (!o->has_empty_slot)
1577 return o_glob(o, n); /* o_save_ptr_helper is inside */
1578 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001579 return o_save_ptr_helper(o, n);
1580}
1581
1582/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001583static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001584{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001585 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001586 int string_start;
1587
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001588 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1589 if (DEBUG_EXPAND)
1590 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001591 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001592 list = (char**)o->data;
1593 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1594 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001595 while (n) {
1596 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001597 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001598 }
1599 return list;
1600}
1601
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001602
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001603/* Expansion can recurse */
1604#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001605static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001606#endif
1607static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001608#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001609#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001610 parse_stream_dquoted(dest, input, dquote_end)
1611#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001612static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001613 o_string *dest,
1614 struct in_str *input,
1615 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001616
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001617/* expand_strvec_to_strvec() takes a list of strings, expands
1618 * all variable references within and returns a pointer to
1619 * a list of expanded strings, possibly with larger number
1620 * of strings. (Think VAR="a b"; echo $VAR).
1621 * This new list is allocated as a single malloc block.
1622 * NULL-terminated list of char* pointers is at the beginning of it,
1623 * followed by strings themself.
1624 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001625
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001626/* Store given string, finalizing the word and starting new one whenever
1627 * we encounter IFS char(s). This is used for expanding variable values.
1628 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1629static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001630{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001631 while (1) {
1632 int word_len = strcspn(str, G.ifs);
1633 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001634 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001635 o_addQstr(output, str, word_len);
1636 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001637 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001638 str += word_len;
1639 }
1640 if (!*str) /* EOL - do not finalize word */
1641 break;
1642 o_addchr(output, '\0');
1643 debug_print_list("expand_on_ifs", output, n);
1644 n = o_save_ptr(output, n);
1645 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001646 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001647 debug_print_list("expand_on_ifs[1]", output, n);
1648 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001649}
1650
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001651/* Expand all variable references in given string, adding words to list[]
1652 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1653 * to be filled). This routine is extremely tricky: has to deal with
1654 * variables/parameters with whitespace, $* and $@, and constructs like
1655 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1656static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001657{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001658 /* or_mask is either 0 (normal case) or 0x80
1659 * (expansion of right-hand side of assignment == 1-element expand.
1660 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001661
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001662 char first_ch, ored_ch;
1663 int i;
1664 const char *val;
1665 char *p;
1666
1667 ored_ch = 0;
1668
1669 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1670 debug_print_list("expand_vars_to_list", output, n);
1671 n = o_save_ptr(output, n);
1672 debug_print_list("expand_vars_to_list[0]", output, n);
1673
1674 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1675#if ENABLE_HUSH_TICK
1676 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001677#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001678#if ENABLE_SH_MATH_SUPPORT
1679 char arith_buf[sizeof(arith_t)*3 + 2];
1680#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001681 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001682 debug_print_list("expand_vars_to_list[1]", output, n);
1683 arg = ++p;
1684 p = strchr(p, SPECIAL_VAR_SYMBOL);
1685
1686 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1687 /* "$@" is special. Even if quoted, it can still
1688 * expand to nothing (not even an empty string) */
1689 if ((first_ch & 0x7f) != '@')
1690 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001691
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 val = NULL;
1693 switch (first_ch & 0x7f) {
1694 /* Highest bit in first_ch indicates that var is double-quoted */
1695 case '$': /* pid */
1696 val = utoa(G.root_pid);
1697 break;
1698 case '!': /* bg pid */
1699 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1700 break;
1701 case '?': /* exitcode */
1702 val = utoa(G.last_return_code);
1703 break;
1704 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001705 if (arg[1] != SPECIAL_VAR_SYMBOL)
1706 /* actually, it's a ${#var} */
1707 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001708 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1709 break;
1710 case '*':
1711 case '@':
1712 i = 1;
1713 if (!G.global_argv[i])
1714 break;
1715 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1716 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001717 smallint sv = output->o_escape;
1718 /* unquoted var's contents should be globbed, so don't escape */
1719 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001720 while (G.global_argv[i]) {
1721 n = expand_on_ifs(output, n, G.global_argv[i]);
1722 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1723 if (G.global_argv[i++][0] && G.global_argv[i]) {
1724 /* this argv[] is not empty and not last:
1725 * put terminating NUL, start new word */
1726 o_addchr(output, '\0');
1727 debug_print_list("expand_vars_to_list[2]", output, n);
1728 n = o_save_ptr(output, n);
1729 debug_print_list("expand_vars_to_list[3]", output, n);
1730 }
1731 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001732 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001733 } else
1734 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1735 * and in this case should treat it like '$*' - see 'else...' below */
1736 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1737 while (1) {
1738 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1739 if (++i >= G.global_argc)
1740 break;
1741 o_addchr(output, '\0');
1742 debug_print_list("expand_vars_to_list[4]", output, n);
1743 n = o_save_ptr(output, n);
1744 }
1745 } else { /* quoted $*: add as one word */
1746 while (1) {
1747 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1748 if (!G.global_argv[++i])
1749 break;
1750 if (G.ifs[0])
1751 o_addchr(output, G.ifs[0]);
1752 }
1753 }
1754 break;
1755 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1756 /* "Empty variable", used to make "" etc to not disappear */
1757 arg++;
1758 ored_ch = 0x80;
1759 break;
1760#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001761 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001762 *p = '\0';
1763 arg++;
1764//TODO: can we just stuff it into "output" directly?
1765 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001766 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001767 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1768 val = subst_result.data;
1769 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001770#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001771#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001772 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001773 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00001774 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00001775 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001776 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001777
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001778 arg++; /* skip '+' */
1779 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00001780 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001781
1782 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1783 exp_str = arg;
1784 while (1) {
1785 unsigned char c = *exp_str++;
1786 if (c == '\0') {
1787 exp_str = NULL;
1788 goto skip_expand;
1789 }
1790 if (isdigit(c))
1791 continue;
1792 if (strchr(" \t+-*/%_", c) != NULL)
1793 continue;
1794 c |= 0x20; /* tolower */
1795 if (c >= 'a' && c <= 'z')
1796 continue;
1797 break;
1798 }
1799 /* We need to expand. Example: "echo $(($a + 1)) $((1 + $((2)) ))" */
1800 {
1801 struct in_str input;
1802 o_string dest = NULL_O_STRING;
1803
1804 setup_string_in_str(&input, arg);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001805 parse_stream_dquoted(NULL, &dest, &input, EOF);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001806 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1807 exp_str = expand_string_to_string(dest.data);
1808 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1809 o_free(&dest);
1810 }
1811 skip_expand:
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001812 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001813 hooks.setvar = arith_set_local_var;
1814 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001815 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1816 free(exp_str);
1817
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001818 if (errcode < 0) {
Mike Frysinger98c52642009-04-02 10:02:37 +00001819 switch (errcode) {
1820 case -3: maybe_die("arith", "exponent less than 0"); break;
1821 case -2: maybe_die("arith", "divide by zero"); break;
1822 case -5: maybe_die("arith", "expression recursion loop detected"); break;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001823 default: maybe_die("arith", "syntax error"); break;
Mike Frysinger98c52642009-04-02 10:02:37 +00001824 }
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001825 }
Mike Frysinger98c52642009-04-02 10:02:37 +00001826 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001827 sprintf(arith_buf, arith_t_fmt, res);
1828 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00001829 break;
1830 }
1831#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001832 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001833 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00001834 bool exp_len = false;
1835 bool exp_null = false;
1836 char *var = arg;
1837 char exp_save = exp_save; /* for compiler */
1838 char exp_op = exp_op; /* for compiler */
1839 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001840 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00001841
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001842 *p = '\0';
1843 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001844
1845 /* prepare for expansions */
1846 if (var[0] == '#') {
1847 /* handle length expansion ${#var} */
1848 exp_len = true;
1849 ++var;
1850 } else {
1851 /* maybe handle parameter expansion */
1852 exp_off = strcspn(var, ":-=+?");
1853 if (!var[exp_off])
1854 exp_off = 0;
1855 if (exp_off) {
1856 exp_save = var[exp_off];
1857 exp_null = exp_save == ':';
1858 exp_word = var + exp_off;
1859 if (exp_null) ++exp_word;
1860 exp_op = *exp_word++;
1861 var[exp_off] = '\0';
1862 }
1863 }
1864
1865 /* lookup the variable in question */
1866 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00001867 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001868 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001869 if (i < G.global_argc)
1870 val = G.global_argv[i];
1871 /* else val remains NULL: $N with too big N */
1872 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001873 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00001874
1875 /* handle any expansions */
1876 if (exp_len) {
1877 debug_printf_expand("expand: length of '%s' = ", val);
1878 val = utoa(val ? strlen(val) : 0);
1879 debug_printf_expand("%s\n", val);
1880 } else if (exp_off) {
1881 /* we need to do an expansion */
1882 int exp_test = (!val || (exp_null && !val[0]));
1883 if (exp_op == '+')
1884 exp_test = !exp_test;
1885 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1886 exp_null ? "true" : "false", exp_test);
1887 if (exp_test) {
1888 if (exp_op == '?')
1889 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1890 else
1891 val = exp_word;
1892
1893 if (exp_op == '=') {
1894 if (isdigit(var[0]) || var[0] == '#') {
1895 maybe_die(var, "special vars cannot assign in this way");
1896 val = NULL;
1897 } else {
1898 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1899 sprintf(new_var, "%s=%s", var, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001900 set_local_var(new_var, -1, 0);
Mike Frysinger6379bb42009-03-28 18:55:03 +00001901 }
1902 }
1903 }
1904 var[exp_off] = exp_save;
1905 }
1906
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001907 arg[0] = first_ch;
1908#if ENABLE_HUSH_TICK
1909 store_val:
1910#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001911 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001912 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001913 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001914 /* unquoted var's contents should be globbed, so don't escape */
1915 smallint sv = output->o_escape;
1916 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001917 n = expand_on_ifs(output, n, val);
1918 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001919 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001920 }
1921 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001922 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001923 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001924 } /* default: */
1925 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001926 if (val) {
1927 o_addQstr(output, val, strlen(val));
1928 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001929 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001930 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00001931 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001932
1933#if ENABLE_HUSH_TICK
1934 o_free(&subst_result);
1935#endif
1936 arg = ++p;
1937 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1938
1939 if (arg[0]) {
1940 debug_print_list("expand_vars_to_list[a]", output, n);
1941 /* this part is literal, and it was already pre-quoted
1942 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001943 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001944 debug_print_list("expand_vars_to_list[b]", output, n);
1945 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1946 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1947 ) {
1948 n--;
1949 /* allow to reuse list[n] later without re-growth */
1950 output->has_empty_slot = 1;
1951 } else {
1952 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00001953 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001954 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001955}
1956
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001957static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001958{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001959 int n;
1960 char **list;
1961 char **v;
1962 o_string output = NULL_O_STRING;
1963
1964 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001965 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001966 /* (unquoted $var will temporarily switch it off) */
1967 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001968 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001969
1970 n = 0;
1971 v = argv;
1972 while (*v) {
1973 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1974 v++;
1975 }
1976 debug_print_list("expand_variables", &output, n);
1977
1978 /* output.data (malloced in one block) gets returned in "list" */
1979 list = o_finalize_list(&output, n);
1980 debug_print_strings("expand_variables[1]", list);
1981 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00001982}
1983
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001984static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001985{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001986 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00001987}
1988
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001989/* Used for expansion of right hand of assignments */
1990/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1991 * "v=/bin/c*" */
1992static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001993{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001994 char *argv[2], **list;
1995
1996 argv[0] = (char*)str;
1997 argv[1] = NULL;
1998 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1999 if (HUSH_DEBUG)
2000 if (!list[0] || list[1])
2001 bb_error_msg_and_die("BUG in varexp2");
2002 /* actually, just move string 2*sizeof(char*) bytes back */
2003 overlapping_strcpy((char*)list, list[0]);
2004 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2005 return (char*)list;
2006}
2007
2008/* Used for "eval" builtin */
2009static char* expand_strvec_to_string(char **argv)
2010{
2011 char **list;
2012
2013 list = expand_variables(argv, 0x80);
2014 /* Convert all NULs to spaces */
2015 if (list[0]) {
2016 int n = 1;
2017 while (list[n]) {
2018 if (HUSH_DEBUG)
2019 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2020 bb_error_msg_and_die("BUG in varexp3");
2021 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2022 n++;
2023 }
2024 }
2025 overlapping_strcpy((char*)list, list[0]);
2026 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2027 return (char*)list;
2028}
2029
2030static char **expand_assignments(char **argv, int count)
2031{
2032 int i;
2033 char **p = NULL;
2034 /* Expand assignments into one string each */
2035 for (i = 0; i < count; i++) {
2036 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2037 }
2038 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002039}
2040
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002041
Eric Andersen25f27032001-04-26 23:22:31 +00002042/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2043 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002044static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002045{
2046 int openfd, mode;
2047 struct redir_struct *redir;
2048
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002049 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002050 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002051 /* something went wrong in the parse. Pretend it didn't happen */
2052 continue;
2053 }
Eric Andersen25f27032001-04-26 23:22:31 +00002054 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002055 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002056 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002057//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002058 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002059 openfd = open_or_warn(p, mode);
2060 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002061 if (openfd < 0) {
2062 /* this could get lost if stderr has been redirected, but
2063 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00002064 return 1;
2065 }
2066 } else {
2067 openfd = redir->dup;
2068 }
2069
2070 if (openfd != redir->fd) {
2071 if (squirrel && redir->fd < 3) {
2072 squirrel[redir->fd] = dup(redir->fd);
2073 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00002074 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00002075 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00002076 } else {
2077 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00002078 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002079 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002080 }
Eric Andersen25f27032001-04-26 23:22:31 +00002081 }
2082 }
2083 return 0;
2084}
2085
2086static void restore_redirects(int squirrel[])
2087{
2088 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002089 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002090 fd = squirrel[i];
2091 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002092 /* We simply die on error */
2093 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002094 }
2095 }
2096}
2097
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002098
Denis Vlasenkoa0e65122009-04-05 23:39:14 +00002099#if !DEBUG_CLEAN
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002100#define free_pipe_list(head, indent) free_pipe_list(head)
2101#define free_pipe(pi, indent) free_pipe(pi)
2102#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002103static void free_pipe_list(struct pipe *head, int indent);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002104
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002105/* Return code is the exit status of the pipe */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002106static void free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002107{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002108 char **p;
2109 struct command *command;
2110 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002111 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002112
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002113 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002114 return;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002115 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2116 for (i = 0; i < pi->num_cmds; i++) {
2117 command = &pi->cmds[i];
2118 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2119 if (command->argv) {
2120 for (a = 0, p = command->argv; *p; a++, p++) {
2121 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2122 }
2123 free_strings(command->argv);
2124 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002125 }
2126 /* not "else if": on syntax error, we may have both! */
2127 if (command->group) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002128 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002129 free_pipe_list(command->group, indent+3);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002130 debug_printf_clean("%s end group\n", indenter(indent));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002131 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002132 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002133#if !BB_MMU
2134 free(command->group_as_string);
2135 command->group_as_string = NULL;
2136#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002137 for (r = command->redirects; r; r = rnext) {
2138 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2139 if (r->dup == -1) {
2140 /* guard against the case >$FOO, where foo is unset or blank */
2141 if (r->rd_filename) {
2142 debug_printf_clean(" %s\n", r->rd_filename);
2143 free(r->rd_filename);
2144 r->rd_filename = NULL;
2145 }
2146 } else {
2147 debug_printf_clean("&%d\n", r->dup);
2148 }
2149 rnext = r->next;
2150 free(r);
2151 }
2152 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002153 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002154 free(pi->cmds); /* children are an array, they get freed all at once */
2155 pi->cmds = NULL;
2156#if ENABLE_HUSH_JOB
2157 free(pi->cmdtext);
2158 pi->cmdtext = NULL;
2159#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002160}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002161
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002162static void free_pipe_list(struct pipe *head, int indent)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002163{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002164 struct pipe *pi, *next;
2165
2166 for (pi = head; pi; pi = next) {
2167#if HAS_KEYWORDS
2168 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2169#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002170 free_pipe(pi, indent);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002171 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2172 next = pi->next;
2173 /*pi->next = NULL;*/
2174 free(pi);
2175 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002176}
2177
2178
2179#if !BB_MMU
2180typedef struct nommu_save_t {
2181 char **new_env;
2182 char **old_env;
2183 char **argv;
2184} nommu_save_t;
2185#else
2186#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2187 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2188#define pseudo_exec(nommu_save, command, argv_expanded) \
2189 pseudo_exec(command, argv_expanded)
2190#endif
2191
Denis Vlasenko05743d72008-02-10 12:10:08 +00002192/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00002193 * Never returns.
2194 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00002195 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002196 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002197static void pseudo_exec_argv(nommu_save_t *nommu_save,
2198 char **argv, int assignment_cnt,
2199 char **argv_expanded) NORETURN;
2200static void pseudo_exec_argv(nommu_save_t *nommu_save,
2201 char **argv, int assignment_cnt,
2202 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00002203{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002204 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002205
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002206 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002207 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002208 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002209
Denis Vlasenko9504e442008-10-29 01:19:15 +00002210 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002211#if BB_MMU
2212 putenv_all(new_env);
2213 free(new_env); /* optional */
2214#else
2215 nommu_save->new_env = new_env;
2216 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002217#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002218 if (argv_expanded) {
2219 argv = argv_expanded;
2220 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00002221 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002222#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002223 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002224#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002225 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002226
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002227 /* On NOMMU, we must never block!
2228 * Example: { sleep 99999 | read line } & echo Ok
2229 * read builtin will block on read syscall, leaving parent blocked
2230 * in vfork. Therefore we can't do this:
2231 */
2232#if BB_MMU
2233 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00002234 * Depending on context, this might be redundant. But it's
2235 * easier to waste a few CPU cycles than it is to figure out
2236 * if this is one of those cases.
2237 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002238 {
2239 int rcode;
2240 const struct built_in_command *x;
2241 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2242 if (strcmp(argv[0], x->cmd) == 0) {
2243 debug_printf_exec("running builtin '%s'\n",
2244 argv[0]);
2245 rcode = x->function(argv);
2246 fflush(NULL);
2247 _exit(rcode);
2248 }
Eric Andersen94ac2442001-05-22 19:05:18 +00002249 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002250 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002251#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00002252
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002253#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002254 /* Check if the command matches any busybox applets */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002255 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002256 int a = find_applet_by_name(argv[0]);
2257 if (a >= 0) {
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002258#if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002259 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002260 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002261 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002262 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002263#endif
2264 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002265 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002266 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2267 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002268 /* If they called chroot or otherwise made the binary no longer
2269 * executable, fall through */
2270 }
2271 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002272#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002273
2274 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002275 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002276 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002277 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002278 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002279}
2280
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002281#if BB_MMU
2282static void reset_traps_to_defaults(void)
2283{
2284 unsigned sig;
2285 int dirty;
2286
2287 if (!G.traps)
2288 return;
2289 dirty = 0;
2290 for (sig = 0; sig < NSIG; sig++) {
2291 if (!G.traps[sig])
2292 continue;
2293 free(G.traps[sig]);
2294 G.traps[sig] = NULL;
2295 /* There is no signal for 0 (EXIT) */
2296 if (sig == 0)
2297 continue;
2298 /* there was a trap handler, we are removing it
2299 * (if sig has non-DFL handling,
2300 * we don't need to do anything) */
2301 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2302 continue;
2303 sigdelset(&G.blocked_set, sig);
2304 dirty = 1;
2305 }
2306 if (dirty)
2307 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2308}
2309#define clean_up_after_re_execute() ((void)0)
2310
2311#else /* !BB_MMU */
2312
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00002313static void re_execute_shell(const char *s) NORETURN;
2314static void re_execute_shell(const char *s)
2315{
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002316 struct variable *cur;
Denis Vlasenko30db43b2009-04-05 02:10:39 +00002317 char **argv, **pp, **pp2;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002318 unsigned cnt;
2319
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002320 /* 1:hush 2:-$<pid> 3:-!<pid> 4:-?<exitcode> 5:-D<depth> <vars...>
2321 * 6:-c 7:<cmd> <argN...> 8:NULL
Denis Vlasenko30db43b2009-04-05 02:10:39 +00002322 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002323 cnt = 8 + G.global_argc;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002324 for (cur = G.top_var; cur; cur = cur->next) {
2325 if (!cur->flg_export || cur->flg_read_only)
2326 cnt += 2;
2327 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002328 G.argv_from_re_execing = pp = xzalloc(sizeof(argv[0]) * cnt);
2329 *pp++ = (char *) G.argv0_for_re_execing;
2330 *pp++ = xasprintf("-$%u", (unsigned) G.root_pid);
2331 *pp++ = xasprintf("-!%u", (unsigned) G.last_bg_pid);
2332 *pp++ = xasprintf("-?%u", (unsigned) G.last_return_code);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00002333#if ENABLE_HUSH_LOOPS
Denis Vlasenko16a0c742009-04-05 01:46:59 +00002334 *pp++ = xasprintf("-D%u", G.depth_of_loop);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00002335#endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002336 for (cur = G.top_var; cur; cur = cur->next) {
2337 if (cur->varstr == hush_version_str)
2338 continue;
2339 if (cur->flg_read_only) {
2340 *pp++ = (char *) "-R";
2341 *pp++ = cur->varstr;
2342 } else if (!cur->flg_export) {
2343 *pp++ = (char *) "-V";
2344 *pp++ = cur->varstr;
2345 }
2346 }
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002347//TODO: pass functions
2348 /* We can pass activated traps here. Say, -Tnn:trap_string
2349 *
2350 * However, POSIX says that subshells reset signals with traps
2351 * to SIG_DFL.
2352 * I tested bash-3.2 and it not only does that with true subshells
2353 * of the form ( list ), but with any forked children shells.
2354 * I set trap "echo W" WINCH; and then tried:
2355 *
2356 * { echo 1; sleep 20; echo 2; } &
2357 * while true; do echo 1; sleep 20; echo 2; break; done &
2358 * true | { echo 1; sleep 20; echo 2; } | cat
2359 *
2360 * In all these cases sending SIGWINCH to the child shell
2361 * did not run the trap. If I add trap "echo V" WINCH;
2362 * _inside_ group (just before echo 1), it works.
2363 *
2364 * I conclude it means we don't need to pass active traps here.
2365 * exec syscall below resets them to SIG_DFL for us.
2366 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002367 *pp++ = (char *) "-c";
2368 *pp++ = (char *) s;
Denis Vlasenko30db43b2009-04-05 02:10:39 +00002369 pp2 = G.global_argv;
2370 while (*pp2)
2371 *pp++ = *pp2++;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00002372 /* *pp = NULL; - is already there */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002373
2374 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002375 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002376 execv(bb_busybox_exec_path, G.argv_from_re_execing);
2377 /* Fallback. Useful for init=/bin/hush usage etc */
2378 if (G.argv0_for_re_execing[0] == '/')
2379 execv(G.argv0_for_re_execing, G.argv_from_re_execing);
2380 xfunc_error_retval = 127;
2381 bb_error_msg_and_die("can't re-execute the shell");
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00002382}
2383
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002384static void clean_up_after_re_execute(void)
2385{
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002386 char **pp = G.argv_from_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002387 if (pp) {
2388 /* Must match re_execute_shell's allocations */
2389 free(pp[1]);
2390 free(pp[2]);
2391 free(pp[3]);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002392#if ENABLE_HUSH_LOOPS
2393 free(pp[4]);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00002394#endif
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002395 free(pp);
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002396 G.argv_from_re_execing = NULL;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002397 }
2398}
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002399#endif
2400
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002401static int run_list(struct pipe *pi);
2402
Denis Vlasenko05743d72008-02-10 12:10:08 +00002403/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00002404 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002405static void pseudo_exec(nommu_save_t *nommu_save,
2406 struct command *command,
2407 char **argv_expanded) NORETURN;
2408static void pseudo_exec(nommu_save_t *nommu_save,
2409 struct command *command,
2410 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002411{
Denis Vlasenko552433b2009-04-04 19:29:21 +00002412 if (command->argv) {
2413 pseudo_exec_argv(nommu_save, command->argv,
2414 command->assignment_cnt, argv_expanded);
2415 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002416
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002417 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00002418 /* Cases when we are here:
2419 * ( list )
2420 * { list } &
2421 * ... | ( list ) | ...
2422 * ... | { list } | ...
2423 */
2424#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002425 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002426 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002427 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002428 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002429 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002430 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002431 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002432#else
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00002433 re_execute_shell(command->group_as_string);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002434#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002435 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002436
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002437 /* Case when we are here: ... | >file */
2438 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002439 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002440}
2441
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002442#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002443static const char *get_cmdtext(struct pipe *pi)
2444{
2445 char **argv;
2446 char *p;
2447 int len;
2448
2449 /* This is subtle. ->cmdtext is created only on first backgrounding.
2450 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002451 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002452 if (pi->cmdtext)
2453 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002454 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002455 if (!argv || !argv[0]) {
2456 pi->cmdtext = xzalloc(1);
2457 return pi->cmdtext;
2458 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002459
2460 len = 0;
2461 do len += strlen(*argv) + 1; while (*++argv);
2462 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002463 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002464 do {
2465 len = strlen(*argv);
2466 memcpy(p, *argv, len);
2467 p += len;
2468 *p++ = ' ';
2469 } while (*++argv);
2470 p[-1] = '\0';
2471 return pi->cmdtext;
2472}
2473
Eric Andersenbafd94f2001-05-02 16:11:59 +00002474static void insert_bg_job(struct pipe *pi)
2475{
2476 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002477 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002478
2479 /* Linear search for the ID of the job to use */
2480 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002481 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002482 if (thejob->jobid >= pi->jobid)
2483 pi->jobid = thejob->jobid + 1;
2484
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002485 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002486 if (!G.job_list) {
2487 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002488 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002489 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002490 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002491 thejob->next = xmalloc(sizeof(*thejob));
2492 thejob = thejob->next;
2493 }
2494
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002495 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002496 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002497 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2498 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2499 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002500// TODO: do we really need to have so many fields which are just dead weight
2501// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002502 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002503 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002504 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002505 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002506 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002507
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002508 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002509 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002510 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00002511 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002512 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002513 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002514}
2515
Eric Andersenbafd94f2001-05-02 16:11:59 +00002516static void remove_bg_job(struct pipe *pi)
2517{
2518 struct pipe *prev_pipe;
2519
Denis Vlasenko87a86552008-07-29 19:43:10 +00002520 if (pi == G.job_list) {
2521 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002522 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002523 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002524 while (prev_pipe->next != pi)
2525 prev_pipe = prev_pipe->next;
2526 prev_pipe->next = pi->next;
2527 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002528 if (G.job_list)
2529 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002530 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002531 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002532}
Eric Andersen028b65b2001-06-28 01:10:11 +00002533
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002534/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002535static void delete_finished_bg_job(struct pipe *pi)
2536{
2537 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002538 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002539 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002540 free(pi);
2541}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002542#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002543
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002544/* Check to see if any processes have exited -- if they
2545 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002546static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002547{
Eric Andersenc798b072001-06-22 06:23:03 +00002548 int attributes;
2549 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002550#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002551 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002552#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002553 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002554 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002555
Denis Vlasenkod5762932009-03-31 11:22:57 +00002556 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2557
Denis Vlasenko7566bae2009-03-31 17:24:49 +00002558 errno = 0;
2559// if (G.handled_SIGCHLD == G.count_SIGCHLD)
2560// /* avoid doing syscall, nothing there anyway */
2561// return rcode;
2562
Eric Andersenc798b072001-06-22 06:23:03 +00002563 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002564 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002565 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002566
Denis Vlasenko1359da62007-04-21 23:27:30 +00002567/* Do we do this right?
2568 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002569 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002570 * [3]+ Stopped sleep 20 | false
2571 * bash-3.00# echo $?
2572 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2573 */
2574
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002575//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2576//are stopped. Testcase: "cat | cat" in a script (not on command line)
2577// + killall -STOP cat
2578
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002579 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00002580 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002581 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00002582 int dead;
2583
2584// i = G.count_SIGCHLD;
2585 childpid = waitpid(-1, &status, attributes);
2586 if (childpid <= 0) {
2587 if (childpid && errno != ECHILD)
2588 bb_perror_msg("waitpid");
2589// else /* Until next SIGCHLD, waitpid's are useless */
2590// G.handled_SIGCHLD = i;
2591 break;
2592 }
2593 dead = WIFEXITED(status) || WIFSIGNALED(status);
2594
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002595#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002596 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002597 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002598 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2599 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002600 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002601 childpid, WTERMSIG(status), WEXITSTATUS(status));
2602 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002603 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002604 childpid, WEXITSTATUS(status));
2605#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002606 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002607 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002608 for (i = 0; i < fg_pipe->num_cmds; i++) {
2609 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2610 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002611 continue;
2612 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2613 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002614 fg_pipe->cmds[i].pid = 0;
2615 fg_pipe->alive_cmds--;
2616 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002617 /* last process gives overall exitstatus */
2618 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002619 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002620 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002621 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002622 fg_pipe->cmds[i].is_stopped = 1;
2623 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002624 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002625 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2626 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2627 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002628 /* All processes in fg pipe have exited/stopped */
2629#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002630 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002631 insert_bg_job(fg_pipe);
2632#endif
2633 return rcode;
2634 }
2635 /* There are still running processes in the fg pipe */
2636 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002637 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002638 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002639 }
2640
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002641#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002642 /* We asked to wait for bg or orphaned children */
2643 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002644 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002645 for (i = 0; i < pi->num_cmds; i++) {
2646 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002647 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002648 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002649 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002650 /* Happens when shell is used as init process (init=/bin/sh) */
2651 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002652 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002653
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002654 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002655 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002656 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002657 pi->cmds[i].pid = 0;
2658 pi->alive_cmds--;
2659 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002660 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00002661 printf(JOB_STATUS_FORMAT, pi->jobid,
2662 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002663 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002664 }
2665 } else {
2666 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002667 pi->cmds[i].is_stopped = 1;
2668 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002669 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002670#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002671 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002672
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002673 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002674}
2675
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002676#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002677static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2678{
2679 pid_t p;
2680 int rcode = checkjobs(fg_pipe);
2681 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002682 p = getpgid(0); /* pgid of our process */
2683 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002684 tcsetpgrp(G_interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002685 return rcode;
2686}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002687#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002688
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002689/* Start all the jobs, but don't wait for anything to finish.
2690 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002691 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00002692 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00002693 * to finish to determine the exit status of the pipe. If the pipe
2694 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002695 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002696 * return value.
2697 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00002698 * Returns -1 only if started some children. IOW: we have to
2699 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00002700 *
2701 * The only case when we do not need to [v]fork is when the pipe
2702 * is single, non-backgrounded, non-subshell command. Examples:
2703 * cmd ; ... { list } ; ...
2704 * cmd && ... { list } && ...
2705 * cmd || ... { list } || ...
2706 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2707 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002708 * with run_list(). If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00002709 *
2710 * Cases when we must fork:
2711 * non-single: cmd | cmd
2712 * backgrounded: cmd & { list } &
2713 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00002714 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002715static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002716{
Denis Vlasenko552433b2009-04-04 19:29:21 +00002717 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002718 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002719 int nextin;
2720 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002721 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002722 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002723 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002724 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002725 /* it is not always needed, but we aim to smaller code */
2726 int squirrel[] = { -1, -1, -1 };
2727 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002728
Denis Vlasenko552433b2009-04-04 19:29:21 +00002729 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002730
Denis Vlasenko552433b2009-04-04 19:29:21 +00002731 USE_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002732 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002733 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002734 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002735
Denis Vlasenko552433b2009-04-04 19:29:21 +00002736 if (pi->num_cmds != 1
2737 || pi->followup == PIPE_BG
2738 || command->grp_type == GRP_SUBSHELL
2739 ) {
2740 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002741 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002742
Denis Vlasenko552433b2009-04-04 19:29:21 +00002743 pi->alive_cmds = 1;
2744
2745 debug_printf_exec(": group:%p argv:'%s'\n",
2746 command->group, command->argv ? command->argv[0] : "NONE");
2747
2748 if (command->group) {
2749#if ENABLE_HUSH_FUNCTIONS
2750 if (command->grp_type == GRP_FUNCTION) {
2751 /* func () { list } */
2752 bb_error_msg("here we ought to remember function definition, and go on");
2753 return EXIT_SUCCESS;
2754 }
2755#endif
2756 /* { list } */
2757 debug_printf("non-subshell group\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002758 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002759 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002760 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00002761 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002762 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002763 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00002764 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002765 }
2766
Denis Vlasenko552433b2009-04-04 19:29:21 +00002767 argv = command->argv ? command->argv : (char **) &null_ptr;
2768 {
2769 const struct built_in_command *x;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002770 char **new_env = NULL;
2771 char **old_env = NULL;
2772
Denis Vlasenko552433b2009-04-04 19:29:21 +00002773 if (argv[command->assignment_cnt] == NULL) {
2774 /* Assignments, but no command */
2775 /* Ensure redirects take effect. Try "a=t >file" */
2776 setup_redirects(command, squirrel);
2777 restore_redirects(squirrel);
2778 /* Set shell variables */
2779 while (*argv) {
2780 p = expand_string_to_string(*argv);
2781 debug_printf_exec("set shell var:'%s'->'%s'\n",
2782 *argv, p);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00002783 set_local_var(p, 0, 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002784 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00002785 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00002786 /* Do we need to flag set_local_var() errors?
2787 * "assignment to readonly var" and "putenv error"
2788 */
2789 return EXIT_SUCCESS;
Eric Andersen78a7c992001-05-15 16:30:25 +00002790 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002791
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002792 /* Expand the rest into (possibly) many strings each */
Denis Vlasenko552433b2009-04-04 19:29:21 +00002793 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002794
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002795 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002796 if (strcmp(argv_expanded[0], x->cmd) != 0)
2797 continue;
2798 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2799 debug_printf("exec with redirects only\n");
2800 setup_redirects(command, NULL);
2801 rcode = EXIT_SUCCESS;
2802 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00002803 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002804 debug_printf("builtin inline %s\n", argv_expanded[0]);
2805 /* XXX setup_redirects acts on file descriptors, not FILEs.
2806 * This is perfect for work that comes after exec().
2807 * Is it really safe for inline use? Experimentally,
2808 * things seem to work with glibc. */
2809 setup_redirects(command, squirrel);
2810 new_env = expand_assignments(argv, command->assignment_cnt);
2811 old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002812 debug_printf_exec(": builtin '%s' '%s'...\n",
2813 x->cmd, argv_expanded[1]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002814 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002815#if ENABLE_FEATURE_SH_STANDALONE
2816 clean_up_and_ret:
2817#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002818 restore_redirects(squirrel);
2819 free_strings_and_unsetenv(new_env, 1);
2820 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002821 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002822 clean_up_and_ret1:
2823 free(argv_expanded);
2824 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2825 debug_printf_exec("run_pipe return %d\n", rcode);
2826 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002827 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002828#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002829 i = find_applet_by_name(argv_expanded[0]);
2830 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2831 setup_redirects(command, squirrel);
2832 save_nofork_data(&G.nofork_save);
2833 new_env = expand_assignments(argv, command->assignment_cnt);
2834 old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002835 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2836 argv_expanded[0], argv_expanded[1]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002837 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2838 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002839 }
2840#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00002841 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00002842 }
2843
Denis Vlasenko552433b2009-04-04 19:29:21 +00002844 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002845 /* NB: argv_expanded may already be created, and that
2846 * might include `cmd` runs! Do not rerun it! We *must*
2847 * use argv_expanded if it's non-NULL */
2848
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002849 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002850 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002851 nextin = 0;
2852
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002853 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00002854#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002855 volatile nommu_save_t nommu_save;
2856 nommu_save.new_env = NULL;
2857 nommu_save.old_env = NULL;
2858 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002859#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002860 command = &(pi->cmds[i]);
2861 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002862 debug_printf_exec(": pipe member '%s' '%s'...\n",
2863 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002864 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002865 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00002866 }
Eric Andersen25f27032001-04-26 23:22:31 +00002867
2868 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002869 pipefds[0] = 0;
2870 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002871 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002872 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00002873
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002874 command->pid = BB_MMU ? fork() : vfork();
2875 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002876#if ENABLE_HUSH_JOB
Denis Vlasenkof9375282009-04-05 19:13:39 +00002877 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
Denis Vlasenkod5762932009-03-31 11:22:57 +00002878
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002879 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00002880 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002881 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002882 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002883 pgrp = pi->pgrp;
2884 if (pgrp < 0) /* true for 1st process only */
2885 pgrp = getpid();
2886 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002887 /* We do it in *every* child, not just first,
2888 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002889 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002890 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002891 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002892#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00002893 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002894 xmove_fd(pipefds[1], 1); /* write end */
2895 if (pipefds[0] > 1)
2896 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00002897 /* Like bash, explicit redirects override pipes,
2898 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002899 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00002900
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002901 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00002902 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2903
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002904 /* Stores to nommu_save list of env vars putenv'ed
2905 * (NOMMU, on MMU we don't need that) */
2906 /* cast away volatility... */
2907 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002908 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002909 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002910
Denis Vlasenkof9375282009-04-05 19:13:39 +00002911 /* parent or error */
2912#if ENABLE_HUSH_JOB
2913 die_sleep = -1; /* restore tty pgrp on xfunc death */
2914#endif
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002915#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002916 /* Clean up after vforked child */
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00002917 clean_up_after_re_execute();
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002918 free(nommu_save.argv);
2919 free_strings_and_unsetenv(nommu_save.new_env, 1);
2920 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002921#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002922 free(argv_expanded);
2923 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002924 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002925 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002926 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002927 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002928 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002929#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002930 /* Second and next children need to know pid of first one */
2931 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002932 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002933#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002934 }
Eric Andersen25f27032001-04-26 23:22:31 +00002935
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002936 if (i)
2937 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002938 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002939 close(pipefds[1]); /* write end */
2940 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002941 nextin = pipefds[0];
2942 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002943
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002944 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002945 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2946 return 1;
2947 }
2948
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002949 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002950 return -1;
2951}
2952
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002953#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002954static void debug_print_tree(struct pipe *pi, int lvl)
2955{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002956 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002957 [PIPE_SEQ] = "SEQ",
2958 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002959 [PIPE_OR ] = "OR" ,
2960 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002961 };
2962 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002963 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002964#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002965 [RES_IF ] = "IF" ,
2966 [RES_THEN ] = "THEN" ,
2967 [RES_ELIF ] = "ELIF" ,
2968 [RES_ELSE ] = "ELSE" ,
2969 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002970#endif
2971#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002972 [RES_FOR ] = "FOR" ,
2973 [RES_WHILE] = "WHILE",
2974 [RES_UNTIL] = "UNTIL",
2975 [RES_DO ] = "DO" ,
2976 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002977#endif
2978#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002979 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002980#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002981#if ENABLE_HUSH_CASE
2982 [RES_CASE ] = "CASE" ,
2983 [RES_MATCH] = "MATCH",
2984 [RES_CASEI] = "CASEI",
2985 [RES_ESAC ] = "ESAC" ,
2986#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002987 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002988 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002989 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002990 static const char *const GRPTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002991 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00002992 "()",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002993#if ENABLE_HUSH_FUNCTIONS
2994 "func()",
2995#endif
2996 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002997
2998 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002999
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003000 pin = 0;
3001 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003002 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3003 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003004 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003005 while (prn < pi->num_cmds) {
3006 struct command *command = &pi->cmds[prn];
3007 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003008
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003009 fprintf(stderr, "%*s prog %d assignment_cnt:%d",
3010 lvl*2, "", prn,
3011 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003012 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003013 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003014 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003015 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003016 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003017 prn++;
3018 continue;
3019 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003020 if (argv) while (*argv) {
3021 fprintf(stderr, " '%s'", *argv);
3022 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003023 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003024 fprintf(stderr, "\n");
3025 prn++;
3026 }
3027 pi = pi->next;
3028 pin++;
3029 }
3030}
3031#endif
3032
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003033/* NB: called by pseudo_exec, and therefore must not modify any
3034 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003035static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003036{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003037#if ENABLE_HUSH_CASE
3038 char *case_word = NULL;
3039#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003040#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003041 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003042 char *for_varname = NULL;
3043 char **for_lcur = NULL;
3044 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00003045#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003046 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003047 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003048#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003049 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003050#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003051 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003052#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003053 /*enum reserved_style*/ smallint rword = RES_NONE;
3054 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003055
Denis Vlasenko87a86552008-07-29 19:43:10 +00003056 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003057
Denis Vlasenko06810332007-05-21 23:30:54 +00003058#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003059 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003060 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3061 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003062 continue;
3063 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003064 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003065 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003066 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003067 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003068 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003069 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003070 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003071 continue;
3072 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003073 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3074 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003075 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003076 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003077 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003078 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003079 }
3080 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003081#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003082
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003083 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00003084 * in order to return, no direct "return" statements please.
3085 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003086
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003087////TODO: ctrl-Z handling needs re-thinking and re-testing
Denis Vlasenkod5762932009-03-31 11:22:57 +00003088
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003089#if ENABLE_HUSH_JOB
3090 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3091 * We are saving state before entering outermost list ("while...done")
3092 * so that ctrl-Z will correctly background _entire_ outermost list,
3093 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003094 if (++G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003095 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003096 /* ctrl-Z forked and we are parent; or ctrl-C.
3097 * Sighandler has longjmped us here */
3098 signal(SIGINT, SIG_IGN);
3099 signal(SIGTSTP, SIG_IGN);
3100 /* Restore level (we can be coming from deep inside
3101 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003102 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003103#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00003104 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003105 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003106 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003107 }
3108#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003109//// if (G.ctrl_z_flag) {
3110//// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3111//// * Remember this child as background job */
3112//// insert_bg_job(pi);
3113//// } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003114 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00003115 bb_putchar('\n');
Denis Vlasenkod5762932009-03-31 11:22:57 +00003116//// }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00003117 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003118 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003119 rcode = 0;
3120 goto ret;
3121 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00003122//// /* ctrl-Z handler will store pid etc in pi */
3123//// G.toplevel_list = pi;
3124//// G.ctrl_z_flag = 0;
3125////#if ENABLE_FEATURE_SH_STANDALONE
3126//// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3127////#endif
3128//// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3129//// signal(SIGINT, handler_ctrl_c);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003130 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00003131#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003132
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003133 /* Go through list of pipes, (maybe) executing them. */
3134 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00003135 if (G.flag_SIGINT)
3136 break;
3137
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003138 IF_HAS_KEYWORDS(rword = pi->res_word;)
3139 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003140 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
3141 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00003142#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00003143 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003144 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00003145 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003146 /* start of a loop: remember where loop starts */
3147 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003148 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003149 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003150#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003151 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003152 if (pi->followup == PIPE_SEQ)
3153 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003154 /* it is "<false> && CMD" or "<true> || CMD"
3155 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003156 continue;
3157 }
3158 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003159 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00003160#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003161 if (cond_code) {
3162 if (rword == RES_THEN) {
3163 /* "if <false> THEN cmd": skip cmd */
3164 continue;
3165 }
3166 } else {
3167 if (rword == RES_ELSE || rword == RES_ELIF) {
3168 /* "if <true> then ... ELSE/ELIF cmd":
3169 * skip cmd and all following ones */
3170 break;
3171 }
3172 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003173#endif
3174#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003175 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003176 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003177 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003178
3179 static const char encoded_dollar_at[] ALIGN1 = {
3180 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3181 }; /* encoded representation of "$@" */
3182 static const char *const encoded_dollar_at_argv[] = {
3183 encoded_dollar_at, NULL
3184 }; /* argv list with one element: "$@" */
3185 char **vals;
3186
3187 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003188 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003189 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003190 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003191 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003192 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003193 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003194 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003195 debug_print_strings("for_list made from", vals);
3196 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003197 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003198 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003199 for_varname = pi->cmds[0].argv[0];
3200 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003201 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003202 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003203 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00003204 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003205 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003206 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003207 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003208 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003209 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003210 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003211 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003212//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003213 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3214 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003215 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003216 if (rword == RES_IN) {
3217 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3218 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003219 if (rword == RES_DONE) {
3220 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003221 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003222#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003223#if ENABLE_HUSH_CASE
3224 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003225 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003226 continue;
3227 }
3228 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003229 char **argv;
3230
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003231 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3232 break;
3233 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003234 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003235 while (*argv) {
3236 char *pattern = expand_string_to_string(*argv);
3237 /* TODO: which FNM_xxx flags to use? */
3238 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3239 free(pattern);
3240 if (cond_code == 0) { /* match! we will execute this branch */
3241 free(case_word); /* make future "word)" stop */
3242 case_word = NULL;
3243 break;
3244 }
3245 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003246 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003247 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003248 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003249 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003250 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003251 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003252 }
3253#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003254 /* Just pressing <enter> in shell should check for jobs.
3255 * OTOH, in non-interactive shell this is useless
3256 * and only leads to extra job checks */
3257 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003258 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00003259 goto check_jobs_and_continue;
3260 continue;
3261 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003262
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003263 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00003264 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003265 * after run_pipe() to collect any background children,
3266 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003267 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003268 {
3269 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003270#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00003271 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003272#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003273 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3274 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003275 /* we only ran a builtin: rcode is already known
3276 * and we don't need to wait for anything. */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003277 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003278#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003279 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003280 if (G.flag_break_continue) {
3281 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003282 /* we might fall into outer *loop*,
3283 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003284 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003285 G.depth_break_continue--;
3286 if (G.depth_break_continue == 0)
3287 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003288 /* else: e.g. "continue 2" should *break* once, *then* continue */
3289 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003290 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003291 goto check_jobs_and_break;
3292 /* "continue": simulate end of loop */
3293 rword = RES_DONE;
3294 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003295 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003296#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003297 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003298 /* what does bash do with attempts to background builtins? */
3299 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003300 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3301 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003302 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003303#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003304 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003305 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003306#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003307 rcode = 0; /* EXIT_SUCCESS */
3308 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003309#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003310 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003311 /* waits for completion, then fg's main shell */
3312 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003313 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003314 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
3315 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003316#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003317 { /* this one just waits for completion */
3318 rcode = checkjobs(pi);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003319 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003320 debug_printf_exec(": checkjobs returned %d\n", rcode);
3321 }
Eric Andersen25f27032001-04-26 23:22:31 +00003322 }
3323 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003324 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00003325 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003326
3327 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00003328#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003329 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003330 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00003331#endif
3332#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003333 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003334 if (rcode) {
3335 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003336 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003337 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003338 }
3339 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003340 if (!rcode) {
3341 check_jobs_and_break:
3342 checkjobs(NULL);
3343 break;
3344 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003345 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003346#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003347 if ((rcode == 0 && pi->followup == PIPE_OR)
3348 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003349 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003350 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003351 }
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00003352
3353 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00003354 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003355 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003356
3357#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00003358//// if (G.ctrl_z_flag) {
3359//// /* ctrl-Z forked somewhere in the past, we are the child,
3360//// * and now we completed running the list. Exit. */
3361//////TODO: _exit?
3362//// exit(rcode);
3363//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003364 ret:
Denis Vlasenkod5762932009-03-31 11:22:57 +00003365 G.run_list_level--;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003366//// if (!G.run_list_level && G_interactive_fd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00003367//// signal(SIGTSTP, SIG_IGN);
3368//// signal(SIGINT, SIG_IGN);
3369//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003370#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00003371 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003372#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003373 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003374 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003375 free(for_list);
3376#endif
3377#if ENABLE_HUSH_CASE
3378 free(case_word);
3379#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003380 return rcode;
3381}
3382
Eric Andersen25f27032001-04-26 23:22:31 +00003383/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003384static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003385{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003386 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003387 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003388 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003389 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003390 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003391 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003392 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00003393 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003394 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003395 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003396 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003397 return rcode;
3398}
3399
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003400
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003401/* Peek ahead in the in_str to find out if we have a "&n" construct,
3402 * as in "2>&1", that represents duplicating a file descriptor.
3403 * Return either -2 (syntax error), -1 (no &), or the number found.
3404 */
3405static int redirect_dup_num(struct in_str *input)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003406{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003407 int ch, d = 0, ok = 0;
3408 ch = i_peek(input);
3409 if (ch != '&') return -1;
3410
3411 i_getch(input); /* get the & */
3412 ch = i_peek(input);
3413 if (ch == '-') {
3414 i_getch(input);
3415 return -3; /* "-" represents "close me" */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003416 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003417 while (isdigit(ch)) {
3418 d = d*10 + (ch-'0');
3419 ok = 1;
3420 i_getch(input);
3421 ch = i_peek(input);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003422 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003423 if (ok) return d;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003424
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003425 bb_error_msg("ambiguous redirect");
3426 return -2;
Eric Andersen78a7c992001-05-15 16:30:25 +00003427}
3428
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003429/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00003430 * for file descriptor duplication, e.g., "2>&1".
3431 * Return code is 0 normally, 1 if a syntax error is detected in src.
3432 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenkof9f74292009-04-03 00:07:05 +00003433static int setup_redirect(struct parse_context *ctx,
3434 int fd,
3435 redir_type style,
3436 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003437{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003438 struct command *command = ctx->command;
Denis Vlasenkof9f74292009-04-03 00:07:05 +00003439 struct redir_struct *redir;
3440 struct redir_struct **redirp;
3441 int dup_num;
3442
3443 /* Check for a '2>&1' type redirect */
3444 dup_num = redirect_dup_num(input);
3445 if (dup_num == -2)
3446 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00003447
3448 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenkof9f74292009-04-03 00:07:05 +00003449 redirp = &command->redirects;
3450 while ((redir = *redirp) != NULL) {
3451 redirp = &(redir->next);
Eric Andersen25f27032001-04-26 23:22:31 +00003452 }
Denis Vlasenkof9f74292009-04-03 00:07:05 +00003453 *redirp = redir = xzalloc(sizeof(*redir));
Denis Vlasenkoff097622007-10-01 10:00:45 +00003454 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003455 /* redir->rd_filename = NULL; */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003456 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003457 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00003458
3459 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3460
Denis Vlasenkof9f74292009-04-03 00:07:05 +00003461 redir->dup = dup_num;
3462 if (dup_num != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00003463 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00003464 * is legit; I postpone that to "run time"
3465 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00003466 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3467 } else {
3468 /* We do _not_ try to open the file that src points to,
3469 * since we need to return and let src be expanded first.
3470 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00003471 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00003472 ctx->pending_redirect = redir;
3473 }
3474 return 0;
3475}
3476
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003477
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003478static struct pipe *new_pipe(void)
3479{
Eric Andersen25f27032001-04-26 23:22:31 +00003480 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003481 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003482 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003483 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003484 return pi;
3485}
3486
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003487/* Command (member of a pipe) is complete. The only possible error here
3488 * is out of memory, in which case xmalloc exits. */
3489static int done_command(struct parse_context *ctx)
3490{
3491 /* The command is really already in the pipe structure, so
3492 * advance the pipe counter and make a new, null command. */
3493 struct pipe *pi = ctx->pipe;
3494 struct command *command = ctx->command;
3495
3496 if (command) {
3497 if (command->group == NULL
3498 && command->argv == NULL
3499 && command->redirects == NULL
3500 ) {
3501 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3502 return pi->num_cmds;
3503 }
3504 pi->num_cmds++;
3505 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3506 } else {
3507 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3508 }
3509
3510 /* Only real trickiness here is that the uncommitted
3511 * command structure is not counted in pi->num_cmds. */
3512 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3513 command = &pi->cmds[pi->num_cmds];
3514 memset(command, 0, sizeof(*command));
3515
3516 ctx->command = command;
3517 /* but ctx->pipe and ctx->list_head remain unchanged */
3518
3519 return pi->num_cmds; /* used only for 0/nonzero check */
3520}
3521
3522static void done_pipe(struct parse_context *ctx, pipe_style type)
3523{
3524 int not_null;
3525
3526 debug_printf_parse("done_pipe entered, followup %d\n", type);
3527 /* Close previous command */
3528 not_null = done_command(ctx);
3529 ctx->pipe->followup = type;
3530 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3531 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3532 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3533
3534 /* Without this check, even just <enter> on command line generates
3535 * tree of three NOPs (!). Which is harmless but annoying.
3536 * IOW: it is safe to do it unconditionally.
3537 * RES_NONE case is for "for a in; do ..." (empty IN set)
3538 * to work, possibly other cases too. */
3539 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3540 struct pipe *new_p;
3541 debug_printf_parse("done_pipe: adding new pipe: "
3542 "not_null:%d ctx->ctx_res_w:%d\n",
3543 not_null, ctx->ctx_res_w);
3544 new_p = new_pipe();
3545 ctx->pipe->next = new_p;
3546 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003547 /* RES_THEN, RES_DO etc are "sticky" -
3548 * they remain set for commands inside if/while.
3549 * This is used to control execution.
3550 * RES_FOR and RES_IN are NOT sticky (needed to support
3551 * cases where variable or value happens to match a keyword):
3552 */
3553#if ENABLE_HUSH_LOOPS
3554 if (ctx->ctx_res_w == RES_FOR
3555 || ctx->ctx_res_w == RES_IN)
3556 ctx->ctx_res_w = RES_NONE;
3557#endif
3558#if ENABLE_HUSH_CASE
3559 if (ctx->ctx_res_w == RES_MATCH)
3560 ctx->ctx_res_w = RES_CASEI;
3561#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003562 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003563 /* Create the memory for command, roughly:
3564 * ctx->pipe->cmds = new struct command;
3565 * ctx->command = &ctx->pipe->cmds[0];
3566 */
3567 done_command(ctx);
3568 }
3569 debug_printf_parse("done_pipe return\n");
3570}
3571
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003572static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003573{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003574 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003575 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003576 /* Create the memory for command, roughly:
3577 * ctx->pipe->cmds = new struct command;
3578 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003579 */
3580 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003581}
3582
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003583
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003584/* If a reserved word is found and processed, parse context is modified
3585 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003586 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003587#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003588struct reserved_combo {
3589 char literal[6];
3590 unsigned char res;
3591 unsigned char assignment_flag;
3592 int flag;
3593};
3594enum {
3595 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003596#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003597 FLAG_IF = (1 << RES_IF ),
3598 FLAG_THEN = (1 << RES_THEN ),
3599 FLAG_ELIF = (1 << RES_ELIF ),
3600 FLAG_ELSE = (1 << RES_ELSE ),
3601 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003602#endif
3603#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003604 FLAG_FOR = (1 << RES_FOR ),
3605 FLAG_WHILE = (1 << RES_WHILE),
3606 FLAG_UNTIL = (1 << RES_UNTIL),
3607 FLAG_DO = (1 << RES_DO ),
3608 FLAG_DONE = (1 << RES_DONE ),
3609 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003610#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003611#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003612 FLAG_MATCH = (1 << RES_MATCH),
3613 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003614#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003615 FLAG_START = (1 << RES_XXXX ),
3616};
3617
3618static const struct reserved_combo* match_reserved_word(o_string *word)
3619{
Eric Andersen25f27032001-04-26 23:22:31 +00003620 /* Mostly a list of accepted follow-up reserved words.
3621 * FLAG_END means we are done with the sequence, and are ready
3622 * to turn the compound list into a command.
3623 * FLAG_START means the word must start a new compound list.
3624 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003625 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003626#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003627 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3628 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3629 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3630 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3631 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3632 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003633#endif
3634#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003635 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3636 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3637 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3638 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3639 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3640 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003641#endif
3642#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003643 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3644 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003645#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003646 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003647 const struct reserved_combo *r;
3648
3649 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3650 if (strcmp(word->data, r->literal) == 0)
3651 return r;
3652 }
3653 return NULL;
3654}
3655static int reserved_word(o_string *word, struct parse_context *ctx)
3656{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003657#if ENABLE_HUSH_CASE
3658 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003659 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003660 };
3661#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003662 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003663
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003664 r = match_reserved_word(word);
3665 if (!r)
3666 return 0;
3667
3668 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003669#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003670 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3671 /* "case word IN ..." - IN part starts first match part */
3672 r = &reserved_match;
3673 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003674#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003675 if (r->flag == 0) { /* '!' */
3676 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003677 syntax("! ! command");
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003678 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003679 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003680 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003681 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003682 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003683 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003684 struct parse_context *old;
3685 old = xmalloc(sizeof(*old));
3686 debug_printf_parse("push stack %p\n", old);
3687 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003688 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003689 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003690 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003691 syntax(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003692 ctx->ctx_res_w = RES_SNTX;
3693 return 1;
3694 }
3695 ctx->ctx_res_w = r->res;
3696 ctx->old_flag = r->flag;
3697 if (ctx->old_flag & FLAG_END) {
3698 struct parse_context *old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003699 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003700 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003701 old = ctx->stack;
3702 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003703 old->command->grp_type = GRP_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003704#if !BB_MMU
3705 o_addstr(&old->as_string, ctx->as_string.data);
3706 o_free_unsafe(&ctx->as_string);
3707 old->command->group_as_string = xstrdup(old->as_string.data);
3708 debug_printf_parse("pop, remembering as:'%s'\n",
3709 old->command->group_as_string);
3710#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003711 *ctx = *old; /* physical copy */
3712 free(old);
3713 }
3714 word->o_assignment = r->assignment_flag;
3715 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003716}
Denis Vlasenko06810332007-05-21 23:30:54 +00003717#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003718
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003719/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003720 * Normal return is 0. Syntax errors return 1.
3721 * Note: on return, word is reset, but not o_free'd!
3722 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003723static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003724{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003725 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003726
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003727 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003728 if (word->length == 0 && word->nonnull == 0) {
3729 debug_printf_parse("done_word return 0: true null, ignored\n");
3730 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003731 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003732 /* If this word wasn't an assignment, next ones definitely
3733 * can't be assignments. Even if they look like ones. */
3734 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3735 && word->o_assignment != WORD_IS_KEYWORD
3736 ) {
3737 word->o_assignment = NOT_ASSIGNMENT;
3738 } else {
3739 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003740 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003741 word->o_assignment = MAYBE_ASSIGNMENT;
3742 }
3743
Eric Andersen25f27032001-04-26 23:22:31 +00003744 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003745 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3746 * only if run as "bash", not "sh" */
3747 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003748 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003749 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003750 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003751 /* "{ echo foo; } echo bar" - bad */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003752 /* NB: bash allows e.g.:
3753 * if true; then { echo foo; } fi
3754 * while if false; then false; fi do break; done
3755 * TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003756 if (command->group) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003757 syntax(word->data);
3758 debug_printf_parse("done_word return 1: syntax error, "
3759 "groups and arglists don't mix\n");
Denis Vlasenko395ae452008-07-14 06:29:38 +00003760 return 1;
3761 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003762#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003763#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003764 if (ctx->ctx_dsemicolon
3765 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3766 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003767 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003768 /* ctx->ctx_res_w = RES_MATCH; */
3769 ctx->ctx_dsemicolon = 0;
3770 } else
3771#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003772 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003773#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003774 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3775 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003776#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003777 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003778 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3779 if (reserved_word(word, ctx)) {
3780 o_reset(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003781 debug_printf_parse("done_word return %d\n",
3782 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003783 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003784 }
Eric Andersen25f27032001-04-26 23:22:31 +00003785 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003786#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003787 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003788 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3789 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003790 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003791 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003792 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003793 char *p = word->data;
3794 while (p[0] == SPECIAL_VAR_SYMBOL
3795 && (p[1] & 0x7f) == '@'
3796 && p[2] == SPECIAL_VAR_SYMBOL
3797 ) {
3798 p += 3;
3799 }
3800 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003801 /* saw no "$@", or not only "$@" but some
3802 * real text is there too */
3803 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003804 * e.g. "", $empty"" etc to not disappear */
3805 o_addchr(word, SPECIAL_VAR_SYMBOL);
3806 o_addchr(word, SPECIAL_VAR_SYMBOL);
3807 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003808 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003809 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003810 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003811 }
Eric Andersen25f27032001-04-26 23:22:31 +00003812
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003813 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003814 ctx->pending_redirect = NULL;
3815
Denis Vlasenko06810332007-05-21 23:30:54 +00003816#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003817 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003818 /* NB: basically, this makes hush see "for v in ..." syntax as if
3819 * as it is "for v; in ...". FOR and IN become two pipe structs
3820 * in parse tree. */
3821 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003822//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003823 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003824 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003825#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003826#if ENABLE_HUSH_CASE
3827 /* Force CASE to have just one word */
3828 if (ctx->ctx_res_w == RES_CASE) {
3829 done_pipe(ctx, PIPE_SEQ);
3830 }
3831#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003832 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003833 return 0;
3834}
3835
Eric Andersen25f27032001-04-26 23:22:31 +00003836/* If a redirect is immediately preceded by a number, that number is
3837 * supposed to tell which file descriptor to redirect. This routine
3838 * looks for such preceding numbers. In an ideal world this routine
3839 * needs to handle all the following classes of redirects...
3840 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3841 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3842 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3843 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3844 * A -1 output from this program means no valid number was found, so the
3845 * caller should use the appropriate default for this redirection.
3846 */
3847static int redirect_opt_num(o_string *o)
3848{
3849 int num;
3850
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003851 if (o->length == 0)
3852 return -1;
3853 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003854 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003855 return -1;
3856 }
3857 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003858 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003859 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003860 return num;
3861}
3862
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003863#if BB_MMU
3864#define parse_stream(pstring, input, end_trigger) \
3865 parse_stream(input, end_trigger)
3866#endif
3867static struct pipe *parse_stream(char **pstring,
3868 struct in_str *input,
3869 int end_trigger);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003870static void parse_and_run_string(const char *s);
Mike Frysingerddbee972009-03-22 22:48:41 +00003871
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003872#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003873static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00003874{
3875 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003876 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003877
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003878 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00003879 pid = BB_MMU ? fork() : vfork();
3880 if (pid < 0)
3881 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003882
Denis Vlasenko05743d72008-02-10 12:10:08 +00003883 if (pid == 0) { /* child */
Denis Vlasenkof9375282009-04-05 19:13:39 +00003884#if ENABLE_HUSH_JOB
3885 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
3886#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003887 /* Process substitution is not considered to be usual
3888 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003889 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
3890 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00003891 bb_signals(0
3892 + (1 << SIGTSTP)
3893 + (1 << SIGTTIN)
3894 + (1 << SIGTTOU)
3895 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003896 close(channel[0]); /* NB: close _first_, then move fd! */
3897 xmove_fd(channel[1], 1);
3898 /* Prevent it from trying to handle ctrl-z etc */
3899 USE_HUSH_JOB(G.run_list_level = 1;)
3900#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00003901 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003902 parse_and_run_string(s);
3903 _exit(G.last_return_code);
3904#else
3905 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00003906 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
3907 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003908 * echo OK
3909 */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00003910 re_execute_shell(s);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003911#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003912 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003913
3914 /* parent */
Denis Vlasenkof9375282009-04-05 19:13:39 +00003915#if ENABLE_HUSH_JOB
3916 die_sleep = -1; /* restore tty pgrp on xfunc death */
3917#endif
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003918 clean_up_after_re_execute();
Eric Andersen25f27032001-04-26 23:22:31 +00003919 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003920 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003921 return pf;
3922}
3923
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003924/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003925static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00003926{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003927 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003928 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003929 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003930
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003931 pf = generate_stream_from_string(s);
3932 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00003933 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003934 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00003935
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003936 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003937 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003938 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003939 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003940 if (ch == '\n') {
3941 eol_cnt++;
3942 continue;
3943 }
3944 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003945 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003946 eol_cnt--;
3947 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003948 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003949 }
3950
3951 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003952 /* Note: we got EOF, and we just close the read end of the pipe.
3953 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003954 * Try these:
3955 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
3956 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00003957 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00003958 fclose(pf);
3959 debug_printf("closed FILE from child. return 0\n");
3960 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003961}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003962#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003963
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003964static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003965 struct in_str *input, int ch)
3966{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003967 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00003968 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003969 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003970 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00003971 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003972 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003973
3974 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003975#if ENABLE_HUSH_FUNCTIONS
3976 if (ch == 'F') { /* function definition? */
3977 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3978 //command->fname = dest->data;
3979 command->grp_type = GRP_FUNCTION;
3980//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3981 memset(dest, 0, sizeof(*dest));
3982 }
3983#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003984 if (command->argv /* word [word](... */
3985 || dest->length /* word(... */
3986 || dest->nonnull /* ""(... */
3987 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003988 syntax(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003989 debug_printf_parse("parse_group return 1: "
3990 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003991 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003992 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00003993 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003994 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00003995 endch = ')';
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003996 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003997 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003998 {
3999#if !BB_MMU
4000 char *as_string = NULL;
4001#endif
4002 pipe_list = parse_stream(&as_string, input, endch);
4003#if !BB_MMU
4004 if (as_string)
4005 o_addstr(&ctx->as_string, as_string);
4006#endif
4007 /* empty ()/{} or parse error? */
4008 if (!pipe_list || pipe_list == ERR_PTR) {
4009#if !BB_MMU
4010 free(as_string);
4011#endif
4012 syntax(NULL);
4013 debug_printf_parse("parse_group return 1: "
4014 "parse_stream returned %p\n", pipe_list);
4015 return 1;
4016 }
4017 command->group = pipe_list;
4018#if !BB_MMU
4019 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4020 command->group_as_string = as_string;
4021 debug_printf_parse("end of group, remembering as:'%s'\n",
4022 command->group_as_string);
4023#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004024 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004025 debug_printf_parse("parse_group return 0\n");
4026 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004027 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004028}
4029
Mike Frysinger98c52642009-04-02 10:02:37 +00004030#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004031/* Subroutines for copying $(...) and `...` things */
4032static void add_till_backquote(o_string *dest, struct in_str *input);
4033/* '...' */
4034static void add_till_single_quote(o_string *dest, struct in_str *input)
4035{
4036 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004037 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004038 if (ch == EOF)
4039 break;
4040 if (ch == '\'')
4041 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004042 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004043 }
4044}
4045/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4046static void add_till_double_quote(o_string *dest, struct in_str *input)
4047{
4048 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004049 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004050 if (ch == '"')
4051 break;
4052 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004053 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004054 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004055 }
4056 if (ch == EOF)
4057 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004058 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004059 if (ch == '`') {
4060 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004061 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004062 continue;
4063 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004064 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004065 }
4066}
4067/* Process `cmd` - copy contents until "`" is seen. Complicated by
4068 * \` quoting.
4069 * "Within the backquoted style of command substitution, backslash
4070 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4071 * The search for the matching backquote shall be satisfied by the first
4072 * backquote found without a preceding backslash; during this search,
4073 * if a non-escaped backquote is encountered within a shell comment,
4074 * a here-document, an embedded command substitution of the $(command)
4075 * form, or a quoted string, undefined results occur. A single-quoted
4076 * or double-quoted string that begins, but does not end, within the
4077 * "`...`" sequence produces undefined results."
4078 * Example Output
4079 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4080 */
4081static void add_till_backquote(o_string *dest, struct in_str *input)
4082{
4083 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004084 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004085 if (ch == '`')
4086 break;
4087 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004088 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004089 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004090 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004091 ch = ch2;
4092 }
4093 if (ch == EOF)
4094 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004095 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004096 }
4097}
4098/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4099 * quoting and nested ()s.
4100 * "With the $(command) style of command substitution, all characters
4101 * following the open parenthesis to the matching closing parenthesis
4102 * constitute the command. Any valid shell script can be used for command,
4103 * except a script consisting solely of redirections which produces
4104 * unspecified results."
4105 * Example Output
4106 * echo $(echo '(TEST)' BEST) (TEST) BEST
4107 * echo $(echo 'TEST)' BEST) TEST) BEST
4108 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4109 */
Mike Frysinger98c52642009-04-02 10:02:37 +00004110static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004111{
4112 int count = 0;
4113 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004114 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004115 if (ch == EOF)
4116 break;
4117 if (ch == '(')
4118 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004119 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00004120 if (--count < 0) {
4121 if (!dbl)
4122 break;
4123 if (i_peek(input) == ')') {
4124 i_getch(input);
4125 break;
4126 }
4127 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004128 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004129 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004130 if (ch == '\'') {
4131 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004132 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004133 continue;
4134 }
4135 if (ch == '"') {
4136 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004137 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004138 continue;
4139 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004140 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
4141 ch = i_getch(input);
4142 if (ch == EOF)
4143 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004144 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004145 continue;
4146 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004147 }
4148}
Mike Frysinger98c52642009-04-02 10:02:37 +00004149#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004150
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004151/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004152#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004153#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004154 handle_dollar(dest, input)
4155#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004156static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004157 o_string *dest,
4158 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00004159{
Mike Frysinger6379bb42009-03-28 18:55:03 +00004160 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004161 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004162 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004163
4164 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004165 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004166 ch = i_getch(input);
4167#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004168 if (as_string) o_addchr(as_string, ch);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004169#endif
Denis Vlasenkod4981312008-07-31 10:34:48 +00004170 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004171 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004172 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004173 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004174 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004175 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004176 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004177 if (!isalnum(ch) && ch != '_')
4178 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004179 ch = i_getch(input);
4180#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004181 if (as_string) o_addchr(as_string, ch);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004182#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004183 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004184 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004185 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004186 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004187 ch = i_getch(input);
4188#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004189 if (as_string) o_addchr(as_string, ch);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004190#endif
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004191 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004192 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004193 o_addchr(dest, ch | quote_mask);
4194 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004195 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004196 case '$': /* pid */
4197 case '!': /* last bg pid */
4198 case '?': /* last exit code */
4199 case '#': /* number of args */
4200 case '*': /* args */
4201 case '@': /* args */
4202 goto make_one_char_var;
4203 case '{': {
4204 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00004205
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004206 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004207 ch = i_getch(input);
4208#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004209 if (as_string) o_addchr(as_string, ch);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004210#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004211 /* XXX maybe someone will try to escape the '}' */
4212 expansion = 0;
4213 first_char = true;
4214 all_digits = false;
4215 while (1) {
4216 ch = i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004217#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004218 if (as_string) o_addchr(as_string, ch);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004219#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004220 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004221 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004222
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004223 if (first_char) {
4224 if (ch == '#')
4225 /* ${#var}: length of var contents */
4226 goto char_ok;
4227 else if (isdigit(ch)) {
4228 all_digits = true;
4229 goto char_ok;
4230 }
4231 }
4232
4233 if (expansion < 2
4234 && ( (all_digits && !isdigit(ch))
4235 || (!all_digits && !isalnum(ch) && ch != '_')
4236 )
4237 ) {
4238 /* handle parameter expansions
4239 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4240 */
4241 if (first_char)
4242 goto case_default;
4243 switch (ch) {
4244 case ':': /* null modifier */
4245 if (expansion == 0) {
4246 debug_printf_parse(": null modifier\n");
4247 ++expansion;
4248 break;
4249 }
4250 goto case_default;
4251#if 0 /* not implemented yet :( */
4252 case '#': /* remove prefix */
4253 case '%': /* remove suffix */
4254 if (expansion == 0) {
4255 debug_printf_parse(": remove suffix/prefix\n");
4256 expansion = 2;
4257 break;
4258 }
4259 goto case_default;
Mike Frysinger98c52642009-04-02 10:02:37 +00004260#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004261 case '-': /* default value */
4262 case '=': /* assign default */
4263 case '+': /* alternative */
4264 case '?': /* error indicate */
4265 debug_printf_parse(": parameter expansion\n");
4266 expansion = 2;
4267 break;
4268 default:
4269 case_default:
4270 syntax("unterminated ${name}");
4271 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4272 return 1;
4273 }
4274 }
4275 char_ok:
4276 debug_printf_parse(": '%c'\n", ch);
4277 o_addchr(dest, ch | quote_mask);
4278 quote_mask = 0;
4279 first_char = false;
4280 }
4281 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4282 break;
4283 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004284#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004285 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004286# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004287 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004288# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004289 ch = i_getch(input);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004290# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004291 if (as_string) o_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004292# endif
4293# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004294 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004295 ch = i_getch(input);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004296# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004297 if (as_string) o_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004298# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004299 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4300 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004301# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004302 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004303# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004304 add_till_closing_paren(dest, input, true);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004305# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004306 if (as_string) {
4307 o_addstr(as_string, dest->data + pos);
4308 o_addchr(as_string, ')');
4309 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004310 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004311# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004312 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004313 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004314 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004315# endif
4316# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004317 //int pos = dest->length;
4318 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4319 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004320# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004321 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004322# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004323 add_till_closing_paren(dest, input, false);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004324# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004325 if (as_string) {
4326 o_addstr(as_string, dest->data + pos);
4327 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004328 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004329# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004330 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4331 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004332# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004333 break;
4334 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004335#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004336 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004337 ch = i_getch(input);
4338#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004339 if (as_string) o_addchr(as_string, ch);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004340#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004341 ch = i_peek(input);
4342 if (isalnum(ch)) { /* it's $_name or $_123 */
4343 ch = '_';
4344 goto make_var;
4345 }
4346 /* else: it's $_ */
4347 /* TODO: */
4348 /* $_ Shell or shell script name; or last cmd name */
4349 /* $- Option flags set by set builtin or shell options (-i etc) */
4350 default:
4351 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004352 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004353 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004354 return 0;
4355}
4356
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004357#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004358#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004359 parse_stream_dquoted(dest, input, dquote_end)
4360#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004361static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004362 o_string *dest,
4363 struct in_str *input,
4364 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004365{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004366 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004367 int next;
4368
4369 again:
4370 ch = i_getch(input);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004371#if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004372 if (as_string && ch != EOF)
4373 o_addchr(as_string, ch);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004374#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004375 if (ch == dquote_end) { /* may be only '"' or EOF */
4376 dest->nonnull = 1;
4377 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004378 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004379 debug_printf_parse("parse_stream_dquoted return 0\n");
4380 return 0;
4381 }
4382 if (ch == EOF) {
4383 syntax("unterminated \"");
4384 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4385 return 1;
4386 }
4387 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004388 if (ch != '\n') {
4389 next = i_peek(input);
4390 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004391 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4392 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004393 if (ch == '\\') {
4394 if (next == EOF) {
4395 syntax("\\<eof>");
4396 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4397 return 1;
4398 }
4399 /* bash:
4400 * "The backslash retains its special meaning [in "..."]
4401 * only when followed by one of the following characters:
4402 * $, `, ", \, or <newline>. A double quote may be quoted
4403 * within double quotes by preceding it with a backslash.
4404 * If enabled, history expansion will be performed unless
4405 * an ! appearing in double quotes is escaped using
4406 * a backslash. The backslash preceding the ! is not removed."
4407 */
4408 if (strchr("$`\"\\", next) != NULL) {
4409 o_addqchr(dest, i_getch(input));
4410 } else {
4411 o_addqchr(dest, '\\');
4412 }
4413 goto again;
4414 }
4415 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004416 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004417 debug_printf_parse("parse_stream_dquoted return 1: "
4418 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004419 return 1;
4420 }
4421 goto again;
4422 }
4423#if ENABLE_HUSH_TICK
4424 if (ch == '`') {
4425 //int pos = dest->length;
4426 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4427 o_addchr(dest, 0x80 | '`');
4428 add_till_backquote(dest, input);
4429 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4430 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004431 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004432 }
4433#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004434 o_addQchr(dest, ch);
4435 if (ch == '='
4436 && (dest->o_assignment == MAYBE_ASSIGNMENT
4437 || dest->o_assignment == WORD_IS_KEYWORD)
4438 && is_assignment(dest->data)
4439 ) {
4440 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4441 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004442 goto again;
4443}
4444
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004445/*
4446 * Scan input until EOF or end_trigger char.
4447 * Return a list of pipes to execute, or NULL on EOF
4448 * or if end_trigger character is met.
4449 * On syntax error, exit is shell is not interactive,
4450 * reset parsing machinery and start parsing anew,
4451 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004452 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004453static struct pipe *parse_stream(char **pstring,
4454 struct in_str *input,
4455 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004456{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004457 struct parse_context ctx;
4458 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004459 int is_in_dquote;
Eric Andersen25f27032001-04-26 23:22:31 +00004460
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004461 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00004462 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004463 * found. When recursing, quote state is passed in via dest->o_escape.
4464 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004465 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4466 end_trigger ? : 'X');
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004467
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004468 G.ifs = get_local_var_value("IFS");
4469 if (G.ifs == NULL)
4470 G.ifs = " \t\n";
4471
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004472 reset:
4473#if ENABLE_HUSH_INTERACTIVE
4474 input->promptmode = 0; /* PS1 */
4475#endif
4476 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4477 initialize_context(&ctx);
4478 is_in_dquote = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004479 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004480 const char *is_ifs;
4481 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004482 int ch;
4483 int next;
4484 int redir_fd;
4485 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004486
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004487 if (is_in_dquote) {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004488 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004489 goto parse_error;
4490 }
4491 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004492 is_in_dquote = 0;
4493 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004494 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004495 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4496 ch, ch, dest.o_escape);
4497 if (ch == EOF) {
4498 struct pipe *pi;
4499 if (done_word(&dest, &ctx)) {
4500 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004501 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004502 o_free(&dest);
4503 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004504 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004505 /* If we got nothing... */
4506// TODO: test script consisting of just "&"
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004507 if (pi->num_cmds == 0
4508 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4509 ) {
4510 free_pipe_list(pi, 0);
4511 pi = NULL;
4512 }
4513 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004514#if !BB_MMU
4515 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4516 if (pstring)
4517 *pstring = ctx.as_string.data;
4518 else
4519 o_free_unsafe(&ctx.as_string);
4520#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004521 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004522 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004523#if !BB_MMU
4524 o_addchr(&ctx.as_string, ch);
4525#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004526 is_ifs = strchr(G.ifs, ch);
4527 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4528 "\\$\"" USE_HUSH_TICK("`") /* always special */
4529 , ch);
4530
4531 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004532 o_addQchr(&dest, ch);
4533 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4534 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004535 && ch == '='
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004536 && is_assignment(dest.data)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004537 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004538 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004539 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004540 continue;
4541 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004542
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004543 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004544 if (done_word(&dest, &ctx)) {
4545 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00004546 }
Denis Vlasenko37181682009-04-03 03:19:15 +00004547 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00004548#if ENABLE_HUSH_CASE
4549 /* "case ... in <newline> word) ..." -
4550 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004551 if (ctx.command->argv == NULL
4552 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00004553 ) {
4554 continue;
4555 }
4556#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00004557 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004558 done_pipe(&ctx, PIPE_SEQ);
4559 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004560 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00004561 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004562 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004563 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004564 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004565 if (end_trigger && end_trigger == ch) {
4566//TODO: disallow "{ cmd }" without semicolon
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004567 if (done_word(&dest, &ctx)) {
4568 goto parse_error;
4569 }
4570 done_pipe(&ctx, PIPE_SEQ);
4571 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004572 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00004573 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004574 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00004575 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004576 debug_printf_parse("parse_stream return %p: "
4577 "end_trigger char found\n",
4578 ctx.list_head);
4579 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004580#if !BB_MMU
4581 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4582 if (pstring)
4583 *pstring = ctx.as_string.data;
4584 else
4585 o_free_unsafe(&ctx.as_string);
4586#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004587 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004588 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004589 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004590 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004591 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004592
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004593 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004594 /* ch is a special char and thus this word
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004595 * cannot be an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004596 dest.o_assignment = NOT_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004597 }
4598
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004599 next = '\0';
4600 if (ch != '\n') {
4601 next = i_peek(input);
4602 }
4603
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004604 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004605 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004606 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004607 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004608 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004609 if (ch == EOF || ch == '\n')
4610 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004611 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004612 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004613 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004614#if !BB_MMU
4615//TODO: go back one char?
4616 o_addchr(&ctx.as_string, '\n');
4617#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004618 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004619 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004620 }
4621 break;
4622 case '\\':
4623 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004624 syntax("\\<eof>");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004625 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004626 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004627 o_addchr(&dest, '\\');
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004628 ch = i_getch(input);
4629 o_addchr(&dest, ch);
4630#if !BB_MMU
4631 o_addchr(&ctx.as_string, ch);
4632#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004633 break;
4634 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004635 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004636 debug_printf_parse("parse_stream parse error: "
4637 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004638 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004639 }
Eric Andersen25f27032001-04-26 23:22:31 +00004640 break;
4641 case '\'':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004642 dest.nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004643 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004644 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004645 if (ch == EOF) {
4646 syntax("unterminated '");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004647 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004648 }
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004649#if !BB_MMU
4650 o_addchr(&ctx.as_string, ch);
4651#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004652 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004653 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004654 if (dest.o_assignment == NOT_ASSIGNMENT)
4655 o_addqchr(&dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004656 else
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004657 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004658 }
Eric Andersen25f27032001-04-26 23:22:31 +00004659 break;
4660 case '"':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004661 dest.nonnull = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004662 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004663 if (dest.o_assignment == NOT_ASSIGNMENT)
4664 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004665 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004666#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004667 case '`': {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004668 //int pos = dest.length;
4669 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4670 o_addchr(&dest, '`');
4671 add_till_backquote(&dest, input);
4672 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4673 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004674 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004675 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004676#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004677 case '>':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004678 redir_fd = redirect_opt_num(&dest);
4679 if (done_word(&dest, &ctx)) {
4680 goto parse_error;
4681 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004682 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00004683 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004684 redir_style = REDIRECT_APPEND;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004685 ch = i_getch(input);
4686#if !BB_MMU
4687 o_addchr(&ctx.as_string, ch);
4688#endif
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004689 }
4690#if 0
4691 else if (next == '(') {
4692 syntax(">(process) not supported");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004693 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004694 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004695#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004696 setup_redirect(&ctx, redir_fd, redir_style, input);
Eric Andersen25f27032001-04-26 23:22:31 +00004697 break;
4698 case '<':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004699 redir_fd = redirect_opt_num(&dest);
4700 if (done_word(&dest, &ctx)) {
4701 goto parse_error;
4702 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004703 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00004704 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004705 redir_style = REDIRECT_HEREIS;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004706 ch = i_getch(input);
4707#if !BB_MMU
4708 o_addchr(&ctx.as_string, ch);
4709#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004710 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004711 redir_style = REDIRECT_IO;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004712 ch = i_getch(input);
4713#if !BB_MMU
4714 o_addchr(&ctx.as_string, ch);
4715#endif
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004716 }
4717#if 0
4718 else if (next == '(') {
4719 syntax("<(process) not supported");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004720 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004721 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004722#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004723 setup_redirect(&ctx, redir_fd, redir_style, input);
Eric Andersen25f27032001-04-26 23:22:31 +00004724 break;
4725 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004726#if ENABLE_HUSH_CASE
4727 case_semi:
4728#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004729 if (done_word(&dest, &ctx)) {
4730 goto parse_error;
4731 }
4732 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004733#if ENABLE_HUSH_CASE
4734 /* Eat multiple semicolons, detect
4735 * whether it means something special */
4736 while (1) {
4737 ch = i_peek(input);
4738 if (ch != ';')
4739 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004740 ch = i_getch(input);
4741#if !BB_MMU
4742 o_addchr(&ctx.as_string, ch);
4743#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004744 if (ctx.ctx_res_w == RES_CASEI) {
4745 ctx.ctx_dsemicolon = 1;
4746 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004747 break;
4748 }
4749 }
4750#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004751 new_cmd:
4752 /* We just finished a cmd. New one may start
4753 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004754 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004755 break;
4756 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004757 if (done_word(&dest, &ctx)) {
4758 goto parse_error;
4759 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004760 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004761 ch = i_getch(input);
4762#if !BB_MMU
4763 o_addchr(&ctx.as_string, ch);
4764#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004765 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004766 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004767 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004768 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004769 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004770 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004771 if (done_word(&dest, &ctx)) {
4772 goto parse_error;
4773 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004774#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004775 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004776 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004777#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004778 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004779 ch = i_getch(input);
4780#if !BB_MMU
4781 o_addchr(&ctx.as_string, ch);
4782#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004783 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004784 } else {
4785 /* we could pick up a file descriptor choice here
4786 * with redirect_opt_num(), but bash doesn't do it.
4787 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004788 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00004789 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004790 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004791 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004792#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004793 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004794 if (ctx.ctx_res_w == RES_MATCH
4795 && ctx.command->argv == NULL /* not (word|(... */
4796 && dest.length == 0 /* not word(... */
4797 && dest.nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004798 ) {
4799 continue;
4800 }
4801#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004802#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004803 if (dest.length != 0 /* not just () but word() */
4804 && dest.nonnull == 0 /* not a"b"c() */
4805 && ctx.command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004806//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004807 && i_peek(input) == ')'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004808 && !match_reserved_word(&dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004809 ) {
4810 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004811 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004812//if !BB_MMU o_addchr(&ctx.as_string...
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004813 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004814//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004815 ch = i_getch(input);
4816 } while (ch == ' ' || ch == '\n');
4817 if (ch != '{') {
4818 syntax("was expecting {");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004819 goto parse_error;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004820 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004821 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004822 }
4823#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004824 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004825 if (parse_group(&dest, &ctx, input, ch) != 0) {
4826 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004827 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004828 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004829 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004830#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004831 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004832 goto case_semi;
4833#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004834 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004835 /* proper use of this character is caught by end_trigger:
4836 * if we see {, we call parse_group(..., end_trigger='}')
4837 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004838 syntax("unexpected } or )");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004839 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00004840 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004841 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004842 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004843 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004844 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004845
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004846 parse_error:
4847 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004848 struct parse_context *pctx;
4849 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004850
4851 /* Clean up allocated tree.
4852 * Samples for finding leaks on syntax error recovery path.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004853 * Run them from interactive shell, watch pmap `pidof hush`.
4854 * while if false; then false; fi do break; done
4855 * (bash accepts it)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004856 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004857 * Samples to catch leaks at execution:
4858 * while if (true | {true;}); then echo ok; fi; do break; done
4859 * 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 +00004860 */
4861 pctx = &ctx;
4862 do {
4863 /* Update pipe/command counts,
4864 * otherwise freeing may miss some */
4865 done_pipe(pctx, PIPE_SEQ);
4866 debug_printf_clean("freeing list %p from ctx %p\n",
4867 pctx->list_head, pctx);
4868 debug_print_tree(pctx->list_head, 0);
4869 free_pipe_list(pctx->list_head, 0);
4870 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004871#if !BB_MMU
4872 o_free_unsafe(&pctx->as_string);
4873#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004874 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004875 if (pctx != &ctx) {
4876 free(pctx);
4877 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004878 IF_HAS_KEYWORDS(pctx = p2;)
4879 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004880 /* Free text, clear all dest fields */
4881 o_free(&dest);
4882 /* If we are not in top-level parse, we return,
4883 * our caller will propagate error.
4884 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004885 if (end_trigger != ';') {
4886#if !BB_MMU
4887 if (pstring)
4888 *pstring = NULL;
4889#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004890 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004891 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004892 /* Discard cached input, force prompt */
4893 input->p = NULL;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00004894 USE_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004895 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004896 }
Eric Andersen25f27032001-04-26 23:22:31 +00004897}
4898
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004899/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004900 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
4901 * end_trigger controls how often we stop parsing
4902 * NUL: parse all, execute, return
4903 * ';': parse till ';' or newline, execute, repeat till EOF
4904 */
4905static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004906{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004907 while (1) {
4908 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004909
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004910 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004911 if (!pipe_list) /* EOF */
4912 break;
4913 debug_print_tree(pipe_list, 0);
4914 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
4915 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004916 }
Eric Andersen25f27032001-04-26 23:22:31 +00004917}
4918
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004919static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004920{
4921 struct in_str input;
4922 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004923 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00004924}
4925
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004926static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004927{
Eric Andersen25f27032001-04-26 23:22:31 +00004928 struct in_str input;
4929 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004930 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00004931}
4932
Denis Vlasenkof9375282009-04-05 19:13:39 +00004933/* Called a few times only (or even once if "sh -c") */
4934static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004935{
Denis Vlasenkof9375282009-04-05 19:13:39 +00004936 unsigned sig;
4937 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004938
Denis Vlasenkof9375282009-04-05 19:13:39 +00004939 mask = (1 << SIGQUIT);
4940 if (G_interactive_fd) {
4941 mask = 0
4942 | (1 << SIGQUIT)
4943 | (1 << SIGTERM)
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00004944//TODO | (1 << SIGHUP)
Denis Vlasenkof9375282009-04-05 19:13:39 +00004945#if ENABLE_HUSH_JOB
4946 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
4947#endif
4948 | (1 << SIGINT)
4949 ;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004950 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00004951 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00004952
Denis Vlasenkof9375282009-04-05 19:13:39 +00004953 if (!second_time)
4954 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
4955 sig = 0;
4956 while (mask) {
4957 if (mask & 1)
4958 sigaddset(&G.blocked_set, sig);
4959 mask >>= 1;
4960 sig++;
4961 }
4962 sigdelset(&G.blocked_set, SIGCHLD);
4963
4964 sigprocmask(SIG_SETMASK, &G.blocked_set,
4965 second_time ? NULL : &G.inherited_set);
4966 /* POSIX allows shell to re-enable SIGCHLD
4967 * even if it was SIG_IGN on entry */
4968// G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
4969 if (!second_time)
4970 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
4971}
4972
4973#if ENABLE_HUSH_JOB
4974/* helper */
4975static void maybe_set_to_sigexit(int sig)
4976{
4977 void (*handler)(int);
4978 /* non_DFL_mask'ed signals are, well, masked,
4979 * no need to set handler for them.
4980 */
4981 if (!((G.non_DFL_mask >> sig) & 1)) {
4982 handler = signal(sig, sigexit);
4983 if (handler == SIG_IGN) /* oops... restore back to IGN! */
4984 signal(sig, handler);
4985 }
4986}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00004987/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00004988static void set_fatal_handlers(void)
4989{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004990 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00004991 if (HUSH_DEBUG) {
4992 maybe_set_to_sigexit(SIGILL );
4993 maybe_set_to_sigexit(SIGFPE );
4994 maybe_set_to_sigexit(SIGBUS );
4995 maybe_set_to_sigexit(SIGSEGV);
4996 maybe_set_to_sigexit(SIGTRAP);
4997 } /* else: hush is perfect. what SEGV? */
4998 maybe_set_to_sigexit(SIGABRT);
4999 /* bash 3.2 seems to handle these just like 'fatal' ones */
5000 maybe_set_to_sigexit(SIGPIPE);
5001 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005002//TODO: disable and move down when proper SIGHUP handling is added
Denis Vlasenkof9375282009-04-05 19:13:39 +00005003 maybe_set_to_sigexit(SIGHUP );
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005004 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00005005 * if we aren't interactive... but in this case
5006 * we never want to restore pgrp on exit, and this fn is not called */
5007 /*maybe_set_to_sigexit(SIGTERM);*/
5008 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00005009}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005010#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00005011
Denis Vlasenkod5762932009-03-31 11:22:57 +00005012static int set_mode(const char cstate, const char mode)
5013{
5014 int state = (cstate == '-' ? 1 : 0);
5015 switch (mode) {
5016 case 'n': G.fake_mode = state; break;
5017 case 'x': /*G.debug_mode = state;*/ break;
5018 default: return EXIT_FAILURE;
5019 }
5020 return EXIT_SUCCESS;
5021}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005022
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00005023int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00005024int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00005025{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005026 static const struct variable const_shell_ver = {
5027 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005028 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005029 .max_len = 1, /* 0 can provoke free(name) */
5030 .flg_export = 1,
5031 .flg_read_only = 1,
5032 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00005033 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005034 int opt;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005035 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005036 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00005037
Denis Vlasenko574f2f42008-02-27 18:41:59 +00005038 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005039 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5040 G.last_return_code = EXIT_SUCCESS;
5041#if !BB_MMU
5042 G.argv0_for_re_execing = argv[0];
5043#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005044 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005045 G.shell_ver = const_shell_ver; /* copying struct here */
5046 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005047 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005048 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5049 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005050 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005051 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005052 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005053 if (e) while (*e) {
5054 char *value = strchr(*e, '=');
5055 if (value) { /* paranoia */
5056 cur_var->next = xzalloc(sizeof(*cur_var));
5057 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00005058 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005059 cur_var->max_len = strlen(*e);
5060 cur_var->flg_export = 1;
5061 }
5062 e++;
5063 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005064 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005065 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenko38f63192007-01-22 09:03:07 +00005066#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00005067 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00005068#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00005069 G.global_argc = argc;
5070 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00005071 /* Initialize some more globals to non-zero values */
5072 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005073#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00005074 if (ENABLE_FEATURE_EDITING)
5075 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005076 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005077#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00005078
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005079 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005080 * block_signals(0) if we are going to execute "sh <script>",
5081 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005082 * If we later decide that we are interactive, we run block_signals(0)
5083 * (or re-run block_signals(1) if we ran block_signals(0) before)
5084 * in order to intercept (more) signals.
5085 */
5086
5087 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005088 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005089 while (1) {
5090 opt = getopt(argc, argv, "c:xins"
5091#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005092 "$:!:?:D:R:V:"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005093#endif
5094 );
5095 if (opt <= 0)
5096 break;
Eric Andersen25f27032001-04-26 23:22:31 +00005097 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005098 case 'c':
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005099 if (!G.root_pid)
5100 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005101 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00005102 if (!argv[optind]) {
5103 /* -c 'script' (no params): prevent empty $0 */
5104 *--G.global_argv = argv[0];
5105 optind--;
5106 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005107 G.global_argc = argc - optind;
Denis Vlasenkof9375282009-04-05 19:13:39 +00005108 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005109 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005110 goto final_return;
5111 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00005112 /* Well, we cannot just declare interactiveness,
5113 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005114 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005115 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005116 case 's':
5117 /* "-s" means "read from stdin", but this is how we always
5118 * operate, so simply do nothing here. */
5119 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005120#if !BB_MMU
5121 case '$':
5122 G.root_pid = xatoi_u(optarg);
5123 break;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005124 case '!':
5125 G.last_bg_pid = xatoi_u(optarg);
5126 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005127 case '?':
5128 G.last_return_code = xatoi_u(optarg);
5129 break;
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005130# if ENABLE_HUSH_LOOPS
Denis Vlasenko16a0c742009-04-05 01:46:59 +00005131 case 'D':
5132 G.depth_of_loop = xatoi_u(optarg);
5133 break;
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005134# endif
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005135 case 'R':
5136 case 'V':
5137 set_local_var(xstrdup(optarg), 0, opt == 'R');
5138 break;
5139#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005140 case 'n':
5141 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00005142 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005143 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005144 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005145#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005146 fprintf(stderr, "Usage: sh [FILE]...\n"
5147 " or: sh -c command [args]...\n\n");
5148 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005149#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005150 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005151#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005152 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005153 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005154
5155 if (!G.root_pid)
5156 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00005157
5158 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005159 if (argv[0] && argv[0][0] == '-') {
5160 FILE *input;
5161 /* XXX what should argv be while sourcing /etc/profile? */
5162 debug_printf("sourcing /etc/profile\n");
5163 input = fopen_for_read("/etc/profile");
5164 if (input != NULL) {
5165 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00005166 block_signals(0); /* 0: called 1st time */
5167 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005168 parse_and_run_file(input);
5169 fclose(input);
5170 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005171 /* bash: after sourcing /etc/profile,
5172 * tries to source (in the given order):
5173 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5174 * stopping of first found. --noprofile turns this off.
5175 * bash also sources ~/.bash_logout on exit.
5176 * If called as sh, skips .bash_XXX files.
5177 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005178 }
5179
Denis Vlasenkof9375282009-04-05 19:13:39 +00005180 if (argv[optind]) {
5181 FILE *input;
5182 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005183 * "bash <script>" (which is never interactive (unless -i?))
5184 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00005185 * If called as sh, does the same but with $ENV.
5186 */
5187 debug_printf("running script '%s'\n", argv[optind]);
5188 G.global_argv = argv + optind;
5189 G.global_argc = argc - optind;
5190 input = xfopen_for_read(argv[optind]);
5191 close_on_exec_on(fileno(input));
5192 if (!signal_mask_is_inited)
5193 block_signals(0); /* 0: called 1st time */
5194 parse_and_run_file(input);
5195#if ENABLE_FEATURE_CLEAN_UP
5196 fclose(input);
5197#endif
5198 goto final_return;
5199 }
5200
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005201 /* Up to here, shell was non-interactive. Now it may become one.
5202 * NB: don't forget to (re)run block_signals(0/1) as needed.
5203 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005204
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005205 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00005206 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00005207 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00005208 * no arguments remaining or the -s flag given
5209 * standard input is a terminal
5210 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00005211 * Refer to Posix.2, the description of the 'sh' utility.
5212 */
5213#if ENABLE_HUSH_JOB
5214 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005215 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
Denis Vlasenkof9375282009-04-05 19:13:39 +00005216 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005217//TODO: "interactive" and "have job control" are two different things.
5218//If tcgetpgrp fails here, "have job control" is false, but "interactive"
5219//should stay on! Currently, we mix these into one.
Denis Vlasenko87a86552008-07-29 19:43:10 +00005220 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00005221 /* try to dup stdin to high fd#, >= 255 */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005222 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5223 if (G_interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005224 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005225 G_interactive_fd = dup(STDIN_FILENO);
5226 if (G_interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005227 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005228 G_interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005229 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005230// TODO: track & disallow any attempts of user
5231// to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005232 }
Eric Andersen25f27032001-04-26 23:22:31 +00005233 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005234 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005235 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00005236 pid_t shell_pgrp;
5237
5238 /* We are indeed interactive shell, and we will perform
5239 * job control. Setting up for that. */
5240
5241 close_on_exec_on(G_interactive_fd);
5242 /* If we were run as 'hush &', sleep until we are
5243 * in the foreground (tty pgrp == our pgrp).
5244 * If we get started under a job aware app (like bash),
5245 * make sure we are now in charge so we don't fight over
5246 * who gets the foreground */
5247 while (1) {
5248 shell_pgrp = getpgrp();
5249 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5250 if (G.saved_tty_pgrp == shell_pgrp)
5251 break;
5252 /* send TTIN to ourself (should stop us) */
5253 kill(- shell_pgrp, SIGTTIN);
5254 }
5255 /* Block some signals */
5256 block_signals(signal_mask_is_inited);
5257 /* Set other signals to restore saved_tty_pgrp */
5258 set_fatal_handlers();
5259 /* Put ourselves in our own process group */
5260 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5261 /* Grab control of the terminal */
5262 tcsetpgrp(G_interactive_fd, getpid());
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00005263 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00005264 * (we reset die_sleep = 0 whereever we [v]fork) */
5265 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005266 if (setjmp(die_jmp)) {
5267 /* xfunc has failed! die die die */
5268 hush_exit(xfunc_error_retval);
5269 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005270 } else if (!signal_mask_is_inited) {
5271 block_signals(0); /* 0: called 1st time */
5272 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005273#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00005274 /* No job control compiled in, only prompt/line editing */
5275 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005276 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5277 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005278 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005279 G_interactive_fd = dup(STDIN_FILENO);
5280 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005281 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005282 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005283 }
5284 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005285 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00005286 close_on_exec_on(G_interactive_fd);
5287 block_signals(signal_mask_is_inited);
5288 } else if (!signal_mask_is_inited) {
5289 block_signals(0);
5290 }
5291#else
5292 /* We have interactiveness code disabled */
5293 if (!signal_mask_is_inited) {
5294 block_signals(0);
5295 }
5296#endif
5297 /* bash:
5298 * if interactive but not a login shell, sources ~/.bashrc
5299 * (--norc turns this off, --rcfile <file> overrides)
5300 */
5301
5302 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00005303 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysingerb2705e12009-03-23 08:44:02 +00005304 printf("Enter 'help' for a list of built-in commands.\n\n");
5305 }
5306
Denis Vlasenkof9375282009-04-05 19:13:39 +00005307 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00005308
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005309 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00005310#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00005311 if (G.cwd != bb_msg_unknown)
5312 free((char*)G.cwd);
5313 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005314 while (cur_var) {
5315 struct variable *tmp = cur_var;
5316 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00005317 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005318 cur_var = cur_var->next;
5319 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00005320 }
Eric Andersen25f27032001-04-26 23:22:31 +00005321#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005322 hush_exit(G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00005323}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00005324
5325
5326#if ENABLE_LASH
5327int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5328int lash_main(int argc, char **argv)
5329{
5330 //bb_error_msg("lash is deprecated, please use hush instead");
5331 return hush_main(argc, argv);
5332}
5333#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005334
5335
5336/*
5337 * Built-ins
5338 */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005339static int builtin_trap(char **argv)
5340{
Denis Vlasenkod5762932009-03-31 11:22:57 +00005341 int i;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005342 int sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005343 char *new_cmd;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005344
5345 if (!G.traps)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005346 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005347
5348 if (!argv[1]) {
5349 /* No args: print all trapped. This isn't 100% correct as we should
5350 * be escaping the cmd so that it can be pasted back in ...
5351 */
5352 for (i = 0; i < NSIG; ++i)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005353 if (G.traps[i])
5354 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005355 return EXIT_SUCCESS;
5356 }
5357
Denis Vlasenkod5762932009-03-31 11:22:57 +00005358 new_cmd = NULL;
5359 i = 0;
5360 /* if first arg is decimal: reset all specified */
5361 sig = bb_strtou(*++argv, NULL, 10);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005362 if (errno == 0) {
5363 int ret;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005364 set_all:
5365 ret = EXIT_SUCCESS;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005366 while (*argv) {
5367 sig = get_signum(*argv++);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005368 if (sig < 0 || sig >= NSIG) {
5369 ret = EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005370 /* mimic bash message exactly */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005371 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5372 continue;
5373 }
5374
Denis Vlasenkod5762932009-03-31 11:22:57 +00005375 free(G.traps[sig]);
5376 G.traps[sig] = xstrdup(new_cmd);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005377
Denis Vlasenkod5762932009-03-31 11:22:57 +00005378 debug_printf("trap: setting SIG%s (%i) to '%s'",
5379 get_signame(sig), sig, G.traps[sig]);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005380
5381 /* There is no signal for 0 (EXIT) */
5382 if (sig == 0)
5383 continue;
5384
5385 if (new_cmd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00005386 sigaddset(&G.blocked_set, sig);
5387 } else {
5388 /* there was a trap handler, we are removing it
5389 * (if sig has non-DFL handling,
5390 * we don't need to do anything) */
5391 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5392 continue;
5393 sigdelset(&G.blocked_set, sig);
5394 }
5395 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005396 }
5397 return ret;
5398 }
5399
5400 /* first arg is "-": reset all specified to default */
5401 /* first arg is "": ignore all specified */
5402 /* everything else: execute first arg upon signal */
Denis Vlasenkod5762932009-03-31 11:22:57 +00005403 if (!argv[1]) {
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005404 bb_error_msg("trap: invalid arguments");
5405 return EXIT_FAILURE;
5406 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00005407 if (LONE_DASH(*argv))
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005408 /* nothing! */;
5409 else
Denis Vlasenkod5762932009-03-31 11:22:57 +00005410 new_cmd = *argv;
5411 argv++;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005412 goto set_all;
5413}
5414
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005415static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005416{
5417 return 0;
5418}
5419
5420static int builtin_test(char **argv)
5421{
5422 int argc = 0;
5423 while (*argv) {
5424 argc++;
5425 argv++;
5426 }
5427 return test_main(argc, argv - argc);
5428}
5429
5430static int builtin_echo(char **argv)
5431{
5432 int argc = 0;
5433 while (*argv) {
5434 argc++;
5435 argv++;
5436 }
5437 return echo_main(argc, argv - argc);
5438}
5439
5440static int builtin_eval(char **argv)
5441{
5442 int rcode = EXIT_SUCCESS;
5443
5444 if (argv[1]) {
5445 char *str = expand_strvec_to_string(argv + 1);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005446 /* bash:
5447 * eval "echo Hi; done" ("done" is syntax error):
5448 * "echo Hi" will not execute too.
5449 */
5450 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005451 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00005452 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005453 }
5454 return rcode;
5455}
5456
5457static int builtin_cd(char **argv)
5458{
5459 const char *newdir;
5460 if (argv[1] == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005461 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5462 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5463 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005464 newdir = getenv("HOME") ? : "/";
5465 } else
5466 newdir = argv[1];
5467 if (chdir(newdir)) {
5468 printf("cd: %s: %s\n", newdir, strerror(errno));
5469 return EXIT_FAILURE;
5470 }
5471 set_cwd();
5472 return EXIT_SUCCESS;
5473}
5474
5475static int builtin_exec(char **argv)
5476{
5477 if (argv[1] == NULL)
5478 return EXIT_SUCCESS; /* bash does this */
5479 {
5480#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005481 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005482#endif
5483// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005484 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005485 /* never returns */
5486 }
5487}
5488
5489static int builtin_exit(char **argv)
5490{
5491// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5492 //puts("exit"); /* bash does it */
5493// TODO: warn if we have background jobs: "There are stopped jobs"
5494// On second consecutive 'exit', exit anyway.
5495 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00005496 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005497 /* mimic bash: exit 123abc == exit 255 + error msg */
5498 xfunc_error_retval = 255;
5499 /* bash: exit -2 == exit 254, no error msg */
5500 hush_exit(xatoi(argv[1]) & 0xff);
5501}
5502
5503static int builtin_export(char **argv)
5504{
5505 const char *value;
5506 char *name = argv[1];
5507
5508 if (name == NULL) {
5509 // TODO:
5510 // ash emits: export VAR='VAL'
5511 // bash: declare -x VAR="VAL"
5512 // (both also escape as needed (quotes, $, etc))
5513 char **e = environ;
5514 if (e)
5515 while (*e)
5516 puts(*e++);
5517 return EXIT_SUCCESS;
5518 }
5519
5520 value = strchr(name, '=');
5521 if (!value) {
5522 /* They are exporting something without a =VALUE */
5523 struct variable *var;
5524
5525 var = get_local_var(name);
5526 if (var) {
5527 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005528 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005529 putenv(var->varstr);
5530 }
5531 /* bash does not return an error when trying to export
5532 * an undefined variable. Do likewise. */
5533 return EXIT_SUCCESS;
5534 }
5535
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005536 set_local_var(xstrdup(name), 1, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005537 return EXIT_SUCCESS;
5538}
5539
5540#if ENABLE_HUSH_JOB
5541/* built-in 'fg' and 'bg' handler */
5542static int builtin_fg_bg(char **argv)
5543{
5544 int i, jobnum;
5545 struct pipe *pi;
5546
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005547 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005548 return EXIT_FAILURE;
5549 /* If they gave us no args, assume they want the last backgrounded task */
5550 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005551 for (pi = G.job_list; pi; pi = pi->next) {
5552 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005553 goto found;
5554 }
5555 }
5556 bb_error_msg("%s: no current job", argv[0]);
5557 return EXIT_FAILURE;
5558 }
5559 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5560 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5561 return EXIT_FAILURE;
5562 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005563 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005564 if (pi->jobid == jobnum) {
5565 goto found;
5566 }
5567 }
5568 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5569 return EXIT_FAILURE;
5570 found:
5571 // TODO: bash prints a string representation
5572 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko34d4d892009-04-04 20:24:37 +00005573 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005574 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005575 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005576 }
5577
5578 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005579 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5580 for (i = 0; i < pi->num_cmds; i++) {
5581 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5582 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005583 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005584 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005585
5586 i = kill(- pi->pgrp, SIGCONT);
5587 if (i < 0) {
5588 if (errno == ESRCH) {
5589 delete_finished_bg_job(pi);
5590 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005591 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00005592 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005593 }
5594
Denis Vlasenko34d4d892009-04-04 20:24:37 +00005595 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005596 remove_bg_job(pi);
5597 return checkjobs_and_fg_shell(pi);
5598 }
5599 return EXIT_SUCCESS;
5600}
5601#endif
5602
5603#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005604static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005605{
5606 const struct built_in_command *x;
5607
Denis Vlasenko34d4d892009-04-04 20:24:37 +00005608 printf("\n"
5609 "Built-in commands:\n"
5610 "------------------\n");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005611 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5612 printf("%s\t%s\n", x->cmd, x->descr);
5613 }
5614 printf("\n\n");
5615 return EXIT_SUCCESS;
5616}
5617#endif
5618
5619#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005620static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005621{
5622 struct pipe *job;
5623 const char *status_string;
5624
Denis Vlasenko87a86552008-07-29 19:43:10 +00005625 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005626 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005627 status_string = "Stopped";
5628 else
5629 status_string = "Running";
5630
5631 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5632 }
5633 return EXIT_SUCCESS;
5634}
5635#endif
5636
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005637static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005638{
5639 puts(set_cwd());
5640 return EXIT_SUCCESS;
5641}
5642
5643static int builtin_read(char **argv)
5644{
5645 char *string;
5646 const char *name = argv[1] ? argv[1] : "REPLY";
Denis Vlasenkoa0e65122009-04-05 23:39:14 +00005647//TODO: check that argv[1] is a valid variable name
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005648
5649 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005650 return set_local_var(string, 0, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005651}
5652
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005653/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5654 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005655 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005656 * set [-abCefhmnuvx] [-o option] [argument...]
5657 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005658 * set -- [argument...]
5659 * set -o
5660 * set +o
5661 * Implementations shall support the options in both their hyphen and
5662 * plus-sign forms. These options can also be specified as options to sh.
5663 * Examples:
5664 * Write out all variables and their values: set
5665 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5666 * Turn on the -x and -v options: set -xv
5667 * Unset all positional parameters: set --
5668 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5669 * Set the positional parameters to the expansion of x, even if x expands
5670 * with a leading '-' or '+': set -- $x
5671 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005672 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005673 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005674static int builtin_set(char **argv)
5675{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005676 int n;
5677 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005678 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005679
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005680 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005681 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00005682 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005683 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005684 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005685 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005686
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005687 do {
5688 if (!strcmp(arg, "--")) {
5689 ++argv;
5690 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005691 }
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005692
5693 if (arg[0] == '+' || arg[0] == '-') {
5694 for (n = 1; arg[n]; ++n)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005695 if (set_mode(arg[0], arg[n]))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005696 goto error;
5697 continue;
5698 }
5699
5700 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005701 } while ((arg = *++argv) != NULL);
5702 /* Now argv[0] is 1st argument */
5703
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005704 /* Only reset global_argv if we didn't process anything */
5705 if (arg == NULL)
5706 return EXIT_SUCCESS;
5707 set_argv:
5708
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005709 /* NB: G.global_argv[0] ($0) is never freed/changed */
5710 g_argv = G.global_argv;
5711 if (G.global_args_malloced) {
5712 pp = g_argv;
5713 while (*++pp)
5714 free(*pp);
5715 g_argv[1] = NULL;
5716 } else {
5717 G.global_args_malloced = 1;
5718 pp = xzalloc(sizeof(pp[0]) * 2);
5719 pp[0] = g_argv[0]; /* retain $0 */
5720 g_argv = pp;
5721 }
5722 /* This realloc's G.global_argv */
5723 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5724
5725 n = 1;
5726 while (*++pp)
5727 n++;
5728 G.global_argc = n;
5729
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005730 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005731
5732 /* Nothing known, so abort */
5733 error:
5734 bb_error_msg("set: %s: invalid option", arg);
5735 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005736}
5737
5738static int builtin_shift(char **argv)
5739{
5740 int n = 1;
5741 if (argv[1]) {
5742 n = atoi(argv[1]);
5743 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005744 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00005745 if (G.global_args_malloced) {
5746 int m = 1;
5747 while (m <= n)
5748 free(G.global_argv[m++]);
5749 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005750 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00005751 memmove(&G.global_argv[1], &G.global_argv[n+1],
5752 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005753 return EXIT_SUCCESS;
5754 }
5755 return EXIT_FAILURE;
5756}
5757
5758static int builtin_source(char **argv)
5759{
5760 FILE *input;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005761
5762 if (argv[1] == NULL)
5763 return EXIT_FAILURE;
5764
5765 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00005766 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005767 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005768 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005769 return EXIT_FAILURE;
5770 }
5771 close_on_exec_on(fileno(input));
5772
5773 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005774 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005775 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00005776 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005777 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005778 fclose(input);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005779 return G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005780}
5781
5782static int builtin_umask(char **argv)
5783{
5784 mode_t new_umask;
5785 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005786 if (arg) {
Mike Frysinger40b8dc42009-03-29 00:50:30 +00005787 new_umask = bb_strtou(arg, NULL, 8);
5788 if (errno)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005789 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005790 } else {
5791 new_umask = umask(0);
5792 printf("%.3o\n", (unsigned) new_umask);
5793 }
5794 umask(new_umask);
5795 return EXIT_SUCCESS;
5796}
5797
Mike Frysingerd690f682009-03-30 06:50:54 +00005798/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005799static int builtin_unset(char **argv)
5800{
Mike Frysingerd690f682009-03-30 06:50:54 +00005801 size_t i;
5802 int ret;
5803 bool var = true;
5804
5805 if (!argv[1])
5806 return EXIT_SUCCESS;
5807
5808 i = 0;
5809 if (argv[1][0] == '-') {
5810 switch (argv[1][1]) {
5811 case 'v': break;
5812 case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
5813 default:
5814 bb_error_msg("unset: %s: invalid option", argv[1]);
5815 return EXIT_FAILURE;
5816 }
5817 ++i;
5818 }
5819
5820 ret = EXIT_SUCCESS;
5821 while (argv[++i]) {
5822 if (var) {
5823 if (unset_local_var(argv[i]))
5824 ret = EXIT_FAILURE;
5825 }
5826#if ENABLE_HUSH_FUNCTIONS
5827 else
5828 unset_local_func(argv[i]);
5829#endif
5830 }
5831 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005832}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005833
Mike Frysinger56bdea12009-03-28 20:01:58 +00005834/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5835static int builtin_wait(char **argv)
5836{
5837 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005838 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00005839
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005840 if (*++argv == NULL) {
5841 /* Don't care about wait results */
5842 /* Note 1: must wait until there are no more children */
5843 /* Note 2: must be interruptible */
5844 /* Examples:
5845 * $ sleep 3 & sleep 6 & wait
5846 * [1] 30934 sleep 3
5847 * [2] 30935 sleep 6
5848 * [1] Done sleep 3
5849 * [2] Done sleep 6
5850 * $ sleep 3 & sleep 6 & wait
5851 * [1] 30936 sleep 3
5852 * [2] 30937 sleep 6
5853 * [1] Done sleep 3
5854 * ^C <-- after ~4 sec from keyboard
5855 * $
5856 */
5857 sigaddset(&G.blocked_set, SIGCHLD);
5858 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5859 while (1) {
5860 checkjobs(NULL);
5861 if (errno == ECHILD)
5862 break;
5863 /* Wait for SIGCHLD or any other signal of interest */
5864 /* sigtimedwait with infinite timeout: */
5865 sig = sigwaitinfo(&G.blocked_set, NULL);
5866 if (sig > 0) {
5867 sig = check_and_run_traps(sig);
5868 if (sig && sig != SIGCHLD) { /* see note 2 */
5869 ret = 128 + sig;
5870 break;
5871 }
5872 }
5873 }
5874 sigdelset(&G.blocked_set, SIGCHLD);
5875 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5876 return ret;
5877 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00005878
Denis Vlasenko7566bae2009-03-31 17:24:49 +00005879 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00005880 while (*argv) {
5881 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00005882 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00005883 /* mimic bash message */
5884 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00005885 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005886 }
5887 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00005888 if (WIFSIGNALED(status))
5889 ret = 128 + WTERMSIG(status);
5890 else if (WIFEXITED(status))
5891 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00005892 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00005893 ret = EXIT_FAILURE;
5894 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00005895 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00005896 ret = 127;
5897 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00005898 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00005899 }
5900
5901 return ret;
5902}
5903
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005904#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005905static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005906{
Denis Vlasenko87a86552008-07-29 19:43:10 +00005907 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005908 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005909 return EXIT_SUCCESS; /* bash compat */
5910 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005911 G.flag_break_continue++; /* BC_BREAK = 1 */
5912 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005913 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005914 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5915 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005916 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00005917 G.flag_break_continue = BC_BREAK;
5918 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005919 }
5920 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005921 if (G.depth_of_loop < G.depth_break_continue)
5922 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005923 return EXIT_SUCCESS;
5924}
5925
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005926static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005927{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005928 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5929 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005930}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005931#endif