blob: 5203f2eefcd2214b70959f47fd889cfbce336379 [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 * Arithmetic Expansion
42 * <(list) and >(list) Process Substitution
Eric Andersen25f27032001-04-26 23:22:31 +000043 * Here Documents ( << word )
44 * Functions
Mike Frysinger25a6ca02009-03-28 13:59:26 +000045 * Tilde Expansion
Mike Frysinger6379bb42009-03-28 18:55:03 +000046 * Parameter Expansion for substring processing ${var#word} ${var%word}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000047 *
48 * Bash stuff maybe optional enable:
49 * &> and >& redirection of stdout+stderr
50 * Brace expansion
51 * reserved words: [[ ]] function select
Mike Frysinger6379bb42009-03-28 18:55:03 +000052 * substrings ${var:1:5}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000053 *
Eric Andersen25f27032001-04-26 23:22:31 +000054 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000055 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000056 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000057 * port selected bugfixes from post-0.49 busybox lash - done?
Eric Andersen83a2ae22001-05-07 17:59:25 +000058 * change { and } from special chars to reserved words
Denis Vlasenkobcb25532008-07-28 23:04:34 +000059 * builtins: return, trap, ulimit
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +000060 * test magic exec with redirection only
Eric Andersen25f27032001-04-26 23:22:31 +000061 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000062 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000063 * propagate syntax errors, die on resource errors?
64 * continuation lines, both explicit and implicit - done?
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000065 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000066 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000067 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000068 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000069
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000070#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenko424f79b2009-03-22 14:23:34 +000071//TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
Denis Vlasenko61befda2008-11-25 01:36:03 +000072//#include "applet_tables.h" doesn't work
Denis Vlasenkobe709c22008-07-28 00:01:16 +000073#include <glob.h>
74/* #include <dmalloc.h> */
75#if ENABLE_HUSH_CASE
76#include <fnmatch.h>
77#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +000078
Denis Vlasenko424f79b2009-03-22 14:23:34 +000079#define HUSH_VER_STR "0.92"
Denis Vlasenkod01ff132007-05-02 21:40:23 +000080
Denis Vlasenko61befda2008-11-25 01:36:03 +000081#if defined SINGLE_APPLET_MAIN
82/* STANDALONE does not make sense, and won't compile */
83#undef CONFIG_FEATURE_SH_STANDALONE
84#undef ENABLE_FEATURE_SH_STANDALONE
85#undef USE_FEATURE_SH_STANDALONE
86#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87#define ENABLE_FEATURE_SH_STANDALONE 0
88#define USE_FEATURE_SH_STANDALONE(...)
89#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
90#endif
91
Denis Vlasenko05743d72008-02-10 12:10:08 +000092#if !BB_MMU && ENABLE_HUSH_TICK
93//#undef ENABLE_HUSH_TICK
94//#define ENABLE_HUSH_TICK 0
95#warning On NOMMU, hush command substitution is dangerous.
96#warning Dont use it for commands which produce lots of output.
97#warning For more info see shell/hush.c, generate_stream_from_list().
98#endif
99
Denis Vlasenko05743d72008-02-10 12:10:08 +0000100#if !ENABLE_HUSH_INTERACTIVE
101#undef ENABLE_FEATURE_EDITING
102#define ENABLE_FEATURE_EDITING 0
103#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000105#endif
106
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000107/* Do we support ANY keywords? */
108#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
109#define HAS_KEYWORDS 1
110#define IF_HAS_KEYWORDS(...) __VA_ARGS__
111#define IF_HAS_NO_KEYWORDS(...)
112#else
113#define HAS_KEYWORDS 0
114#define IF_HAS_KEYWORDS(...)
115#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
116#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000117
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000118/* Keep unconditionally on for now */
119#define HUSH_DEBUG 1
120/* In progress... */
121#define ENABLE_HUSH_FUNCTIONS 0
122
123
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000124/* If you comment out one of these below, it will be #defined later
125 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000126#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000127/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000128#define debug_printf_parse(...) do {} while (0)
129#define debug_print_tree(a, b) do {} while (0)
130#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000131#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000132#define debug_printf_jobs(...) do {} while (0)
133#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000134#define debug_printf_glob(...) do {} while (0)
135#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000136#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000137#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000138
139#ifndef debug_printf
140#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000141#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000142
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000143#ifndef debug_printf_parse
144#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000145#endif
146
147#ifndef debug_printf_exec
148#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
149#endif
150
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000151#ifndef debug_printf_env
152#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
153#endif
154
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000155#ifndef debug_printf_jobs
156#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000157#define DEBUG_JOBS 1
158#else
159#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000160#endif
161
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000162#ifndef debug_printf_expand
163#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
164#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000165#else
166#define DEBUG_EXPAND 0
167#endif
168
169#ifndef debug_printf_glob
170#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
171#define DEBUG_GLOB 1
172#else
173#define DEBUG_GLOB 0
174#endif
175
176#ifndef debug_printf_list
177#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000178#endif
179
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000180#ifndef debug_printf_subst
181#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
182#endif
183
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000184#ifndef debug_printf_clean
185/* broken, of course, but OK for testing */
186static const char *indenter(int i)
187{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000188 static const char blanks[] ALIGN1 =
189 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000190 return &blanks[sizeof(blanks) - i - 1];
191}
192#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000193#define DEBUG_CLEAN 1
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 Vlasenkoccce59d2008-06-16 14:35:57 +0000211/* suppress "warning: no previous prototype..." */
212void *xxmalloc(int lineno, size_t size);
213void *xxrealloc(int lineno, void *ptr, size_t size);
214char *xxstrdup(int lineno, const char *str);
215void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000216void *xxmalloc(int lineno, size_t size)
217{
218 void *ptr = xmalloc((size + 0xff) & ~0xff);
219 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
220 return ptr;
221}
222void *xxrealloc(int lineno, void *ptr, size_t size)
223{
224 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
225 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
226 return ptr;
227}
228char *xxstrdup(int lineno, const char *str)
229{
230 char *ptr = xstrdup(str);
231 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
232 return ptr;
233}
234void xxfree(void *ptr)
235{
236 fprintf(stderr, "free %p\n", ptr);
237 free(ptr);
238}
239#define xmalloc(s) xxmalloc(__LINE__, s)
240#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
241#define xstrdup(s) xxstrdup(__LINE__, s)
242#define free(p) xxfree(p)
243#endif
244
245
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000246static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000247
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000248#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000249
Denis Vlasenko5703c222008-06-15 11:49:42 +0000250#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000251#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000252
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000253typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000254 REDIRECT_INPUT = 1,
255 REDIRECT_OVERWRITE = 2,
256 REDIRECT_APPEND = 3,
257 REDIRECT_HEREIS = 4,
258 REDIRECT_IO = 5
259} redir_type;
260
Denis Vlasenko55789c62008-06-18 16:30:42 +0000261/* The descrip member of this structure is only used to make
262 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000263static const struct {
264 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000265 signed char default_fd;
266 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000267} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000268 { 0, 0, "()" },
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_RDONLY, -1, "<<" },
273 { O_RDWR, 1, "<>" }
274};
275
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000276typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000277 PIPE_SEQ = 1,
278 PIPE_AND = 2,
279 PIPE_OR = 3,
280 PIPE_BG = 4,
281} pipe_style;
282
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000283typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000284 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000285#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000286 RES_IF ,
287 RES_THEN ,
288 RES_ELIF ,
289 RES_ELSE ,
290 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000291#endif
292#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000293 RES_FOR ,
294 RES_WHILE ,
295 RES_UNTIL ,
296 RES_DO ,
297 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000298#endif
299#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000300 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000301#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000302#if ENABLE_HUSH_CASE
303 RES_CASE ,
304 /* two pseudo-keywords support contrived "case" syntax: */
305 RES_MATCH , /* "word)" */
306 RES_CASEI , /* "this command is inside CASE" */
307 RES_ESAC ,
308#endif
309 RES_XXXX ,
310 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000311} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000312
Eric Andersen25f27032001-04-26 23:22:31 +0000313struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000314 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000315 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000316 int fd; /* file descriptor being redirected */
317 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000318 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000319};
320
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000321struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000322 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000323 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000324 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000325 smallint grp_type; /* GRP_xxx */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000326 struct pipe *group; /* if non-NULL, this "prog" is {} group,
327 * subshell, or a compound statement */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000328 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000329 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000330};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000331/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
332 * and on execution these are substituted with their values.
333 * Substitution can make _several_ words out of one argv[n]!
334 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000335 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000336 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000337#define GRP_NORMAL 0
338#define GRP_SUBSHELL 1
339#if ENABLE_HUSH_FUNCTIONS
340#define GRP_FUNCTION 2
341#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000342
343struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000344 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000345 int num_cmds; /* total number of commands in job */
346 int alive_cmds; /* number of commands running (not exited) */
347 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000348#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000349 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000350 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000351 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000352#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000353 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000354 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000355 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
356 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000357};
358
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000359/* This holds pointers to the various results of parsing */
360struct parse_context {
361 struct command *command;
362 struct pipe *list_head;
363 struct pipe *pipe;
364 struct redir_struct *pending_redirect;
365#if HAS_KEYWORDS
366 smallint ctx_res_w;
367 smallint ctx_inverted; /* "! cmd | cmd" */
368#if ENABLE_HUSH_CASE
369 smallint ctx_dsemicolon; /* ";;" seen */
370#endif
371 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
372 struct parse_context *stack;
373#endif
374};
375
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000376/* On program start, environ points to initial environment.
377 * putenv adds new pointers into it, unsetenv removes them.
378 * Neither of these (de)allocates the strings.
379 * setenv allocates new strings in malloc space and does putenv,
380 * and thus setenv is unusable (leaky) for shell's purposes */
381#define setenv(...) setenv_is_leaky_dont_use()
382struct variable {
383 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000384 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000385 int max_len; /* if > 0, name is part of initial env; else name is malloced */
386 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000387 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000388};
389
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000390typedef struct o_string {
Eric Andersen25f27032001-04-26 23:22:31 +0000391 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000392 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000393 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000394 /* Misnomer! it's not "quoting", it's "protection against globbing"!
395 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000396 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000397 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000398 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000399 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000400 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000401} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000402enum {
403 MAYBE_ASSIGNMENT = 0,
404 DEFINITELY_ASSIGNMENT = 1,
405 NOT_ASSIGNMENT = 2,
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000406 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000407};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000408/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000409#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000410
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000411/* I can almost use ordinary FILE*. Is open_memstream() universally
Eric Andersen25f27032001-04-26 23:22:31 +0000412 * available? Where is it documented? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000413typedef struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000414 const char *p;
415 /* eof_flag=1: last char in ->p is really an EOF */
416 char eof_flag; /* meaningless if ->p == NULL */
417 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000418#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000419 smallint promptme;
420 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000421#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000422 FILE *file;
423 int (*get) (struct in_str *);
424 int (*peek) (struct in_str *);
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000425} in_str;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000426#define i_getch(input) ((input)->get(input))
427#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000428
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000429enum {
430 CHAR_ORDINARY = 0,
431 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
432 CHAR_IFS = 2, /* treated as ordinary if quoted */
433 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000434};
435
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000436enum {
437 BC_BREAK = 1,
438 BC_CONTINUE = 2,
439};
440
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000441
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000442/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000443/* Sorted roughly by size (smaller offsets == smaller code) */
444struct globals {
445#if ENABLE_HUSH_INTERACTIVE
446 /* 'interactive_fd' is a fd# open to ctty, if we have one
447 * _AND_ if we decided to act interactively */
448 int interactive_fd;
449 const char *PS1;
450 const char *PS2;
451#endif
452#if ENABLE_FEATURE_EDITING
453 line_input_t *line_input_state;
454#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000455 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000456 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000457#if ENABLE_HUSH_JOB
458 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000459 pid_t saved_tty_pgrp;
460 int last_jobid;
461 struct pipe *job_list;
462 struct pipe *toplevel_list;
463 smallint ctrl_z_flag;
464#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000465#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000466 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000467#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000468 smallint fake_mode;
469 /* these three support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000470 smalluint last_return_code;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000471 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000472 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000473 /* how many non-NULL argv's we have. NB: $# + 1 */
474 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000475 char **global_argv;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000476#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000477 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000478 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000479#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000480 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000483 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000484#if ENABLE_FEATURE_SH_STANDALONE
485 struct nofork_save_area nofork_save;
486#endif
487#if ENABLE_HUSH_JOB
488 sigjmp_buf toplevel_jb;
489#endif
490 unsigned char charmap[256];
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
492};
493
494#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000495/* Not #defining name to G.name - this quickly gets unwieldy
496 * (too many defines). Also, I actually prefer to see when a variable
497 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000498#define INIT_G() do { \
499 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
500} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000501
502
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000503/* Function prototypes for builtins */
504static int builtin_cd(char **argv);
505static int builtin_echo(char **argv);
506static int builtin_eval(char **argv);
507static int builtin_exec(char **argv);
508static int builtin_exit(char **argv);
509static int builtin_export(char **argv);
510#if ENABLE_HUSH_JOB
511static int builtin_fg_bg(char **argv);
512static int builtin_jobs(char **argv);
513#endif
514#if ENABLE_HUSH_HELP
515static int builtin_help(char **argv);
516#endif
517static int builtin_pwd(char **argv);
518static int builtin_read(char **argv);
519static int builtin_test(char **argv);
520static int builtin_true(char **argv);
521static int builtin_set(char **argv);
Mike Frysingerad88d5a2009-03-28 13:44:51 +0000522static int builtin_set_mode(const char, const char);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000523static int builtin_shift(char **argv);
524static int builtin_source(char **argv);
525static int builtin_umask(char **argv);
526static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000527static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000528#if ENABLE_HUSH_LOOPS
529static int builtin_break(char **argv);
530static int builtin_continue(char **argv);
531#endif
532//static int builtin_not_written(char **argv);
533
534/* Table of built-in functions. They can be forked or not, depending on
535 * context: within pipes, they fork. As simple commands, they do not.
536 * When used in non-forking context, they can change global variables
537 * in the parent shell process. If forked, of course they cannot.
538 * For example, 'unset foo | whatever' will parse and run, but foo will
539 * still be set at the end. */
540struct built_in_command {
541 const char *cmd;
542 int (*function)(char **argv);
543#if ENABLE_HUSH_HELP
544 const char *descr;
545#define BLTIN(cmd, func, help) { cmd, func, help }
546#else
547#define BLTIN(cmd, func, help) { cmd, func }
548#endif
549};
550
551/* For now, echo and test are unconditionally enabled.
552 * Maybe make it configurable? */
553static const struct built_in_command bltins[] = {
554 BLTIN("." , builtin_source, "Run commands in a file"),
555 BLTIN(":" , builtin_true, "No-op"),
556 BLTIN("[" , builtin_test, "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000557#if ENABLE_HUSH_JOB
558 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
559#endif
560#if ENABLE_HUSH_LOOPS
561 BLTIN("break" , builtin_break, "Exit from a loop"),
562#endif
563 BLTIN("cd" , builtin_cd, "Change directory"),
564#if ENABLE_HUSH_LOOPS
565 BLTIN("continue", builtin_continue, "Start new loop iteration"),
566#endif
567 BLTIN("echo" , builtin_echo, "Write to stdout"),
568 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
569 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
570 BLTIN("exit" , builtin_exit, "Exit"),
571 BLTIN("export", builtin_export, "Set environment variable"),
572#if ENABLE_HUSH_JOB
573 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
574 BLTIN("jobs" , builtin_jobs, "List active jobs"),
575#endif
576 BLTIN("pwd" , builtin_pwd, "Print current directory"),
577 BLTIN("read" , builtin_read, "Input environment variable"),
578// BLTIN("return", builtin_not_written, "Return from a function"),
579 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
580 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
581// BLTIN("trap" , builtin_not_written, "Trap signals"),
582 BLTIN("test" , builtin_test, "Test condition"),
583// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
584 BLTIN("umask" , builtin_umask, "Set file creation mask"),
585 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Mike Frysinger56bdea12009-03-28 20:01:58 +0000586 BLTIN("wait" , builtin_wait, "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000587#if ENABLE_HUSH_HELP
588 BLTIN("help" , builtin_help, "List shell built-in commands"),
589#endif
590};
591
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000592
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000593/* Normal */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000594static void maybe_die(const char *notice, const char *msg)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000595{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000596 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000597 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000598 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000599 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
600#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +0000601 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000602#endif
Mike Frysinger6379bb42009-03-28 18:55:03 +0000603 fp(msg ? "%s: %s" : notice, notice, msg);
604}
Mike Frysinger5a828452009-03-28 19:09:04 +0000605#if 1
606#define syntax(msg) maybe_die("syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000607#else
Mike Frysinger5a828452009-03-28 19:09:04 +0000608/* Debug -- trick gcc to expand __LINE__ and convert to string */
609#define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
610#define _syntax(msg, line) __syntax(msg, line)
611#define syntax(msg) _syntax(msg, __LINE__)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000612#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000613
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000614static int glob_needed(const char *s)
615{
616 while (*s) {
617 if (*s == '\\')
618 s++;
619 if (*s == '*' || *s == '[' || *s == '?')
620 return 1;
621 s++;
622 }
623 return 0;
624}
625
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000626static int is_assignment(const char *s)
627{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000628 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000629 return 0;
630 s++;
631 while (isalnum(*s) || *s == '_')
632 s++;
633 return *s == '=';
634}
635
Denis Vlasenko55789c62008-06-18 16:30:42 +0000636/* Replace each \x with x in place, return ptr past NUL. */
637static char *unbackslash(char *src)
638{
639 char *dst = src;
640 while (1) {
641 if (*src == '\\')
642 src++;
643 if ((*dst++ = *src++) == '\0')
644 break;
645 }
646 return dst;
647}
648
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000649static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000650{
651 int i;
652 unsigned count1;
653 unsigned count2;
654 char **v;
655
656 v = strings;
657 count1 = 0;
658 if (v) {
659 while (*v) {
660 count1++;
661 v++;
662 }
663 }
664 count2 = 0;
665 v = add;
666 while (*v) {
667 count2++;
668 v++;
669 }
670 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
671 v[count1 + count2] = NULL;
672 i = count2;
673 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000674 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000675 return v;
676}
677
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000678static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000679{
680 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000681 v[0] = add;
682 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000683 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000684}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000685
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000686static void putenv_all(char **strings)
687{
688 if (!strings)
689 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000690 while (*strings) {
691 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000692 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000693 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000694}
695
696static char **putenv_all_and_save_old(char **strings)
697{
698 char **old = NULL;
699 char **s = strings;
700
701 if (!strings)
702 return old;
703 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000704 char *v, *eq;
705
706 eq = strchr(*strings, '=');
707 if (eq) {
708 *eq = '\0';
709 v = getenv(*strings);
710 *eq = '=';
711 if (v) {
712 /* v points to VAL in VAR=VAL, go back to VAR */
713 v -= (eq - *strings) + 1;
714 old = add_string_to_strings(old, v);
715 }
716 }
717 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000718 }
719 putenv_all(s);
720 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000721}
722
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000723static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000724{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000725 char **v;
726
727 if (!strings)
728 return;
729
730 v = strings;
731 while (*v) {
732 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000733 debug_printf_env("unsetenv '%s'\n", *v);
734 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000735 }
736 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000737 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000738 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000739}
740
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000741static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000742{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000743 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000744}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000745
746
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000747/* Signals are grouped, we handle them in batches */
748static void set_misc_sighandler(void (*handler)(int))
749{
750 bb_signals(0
751 + (1 << SIGINT)
752 + (1 << SIGQUIT)
753 + (1 << SIGTERM)
754 , handler);
755}
756
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000757#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000758
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000759static void set_fatal_sighandler(void (*handler)(int))
760{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000761 bb_signals(0
762 + (1 << SIGILL)
763 + (1 << SIGTRAP)
764 + (1 << SIGABRT)
765 + (1 << SIGFPE)
766 + (1 << SIGBUS)
767 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000768 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000769 + (1 << SIGHUP)
770 + (1 << SIGPIPE)
771 + (1 << SIGALRM)
772 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000773}
774static void set_jobctrl_sighandler(void (*handler)(int))
775{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000776 bb_signals(0
777 + (1 << SIGTSTP)
778 + (1 << SIGTTIN)
779 + (1 << SIGTTOU)
780 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000781}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000782/* SIGCHLD is special and handled separately */
783
784static void set_every_sighandler(void (*handler)(int))
785{
786 set_fatal_sighandler(handler);
787 set_jobctrl_sighandler(handler);
788 set_misc_sighandler(handler);
789 signal(SIGCHLD, handler);
790}
791
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000792static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000793{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000794 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000795// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000796 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000797}
798
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000799static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000800{
801 pid_t pid;
802
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000803 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Mike Frysingerbfc0fae2009-03-26 18:14:16 +0000804
805 if (!BB_MMU) {
806 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
807 return;
808 }
809
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000810 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000811 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000812 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000813 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000814 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000815 if (ENABLE_HUSH_JOB)
816 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000817 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000818 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000819 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000820 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000821 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000822 /* return to nofork, it will eventually exit now,
823 * not return back to shell */
824 return;
825 }
826 /* parent */
827 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000828 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000829 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000830 /* parent needs to longjmp out of running nofork.
831 * we will "return" exitcode 0, with child put in background */
832// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000833 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000834 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000835}
836
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000837/* Restores tty foreground process group, and exits.
838 * May be called as signal handler for fatal signal
839 * (will faithfully resend signal to itself, producing correct exit state)
840 * or called directly with -EXITCODE.
841 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000842static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000843static void sigexit(int sig)
844{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000845 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000846 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000847
Denis Vlasenko87a86552008-07-29 19:43:10 +0000848#if ENABLE_HUSH_INTERACTIVE
849 if (G.interactive_fd)
850 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
851#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000852
853 /* Not a signal, just exit */
854 if (sig <= 0)
855 _exit(- sig);
856
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000857 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000858}
859
860/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000861static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000862static void hush_exit(int exitcode)
863{
864 fflush(NULL); /* flush all streams */
865 sigexit(- (exitcode & 0xff));
866}
867
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000868#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000869
870#define set_fatal_sighandler(handler) ((void)0)
871#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000872#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000873
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000874#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000875
876
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000877static const char *set_cwd(void)
878{
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000879 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
880 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000881 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000882 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000883 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
884 if (!G.cwd)
885 G.cwd = bb_msg_unknown;
886 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000887}
888
Denis Vlasenko83506862007-11-23 13:11:42 +0000889
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000890/* Get/check local shell variables */
891static struct variable *get_local_var(const char *name)
892{
893 struct variable *cur;
894 int len;
895
896 if (!name)
897 return NULL;
898 len = strlen(name);
899 for (cur = G.top_var; cur; cur = cur->next) {
900 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
901 return cur;
902 }
903 return NULL;
904}
905
906/* Basically useful version until someone wants to get fancier,
907 * see the bash man page under "Parameter Expansion" */
908static const char *lookup_param(const char *src)
909{
910 struct variable *var = get_local_var(src);
911 if (var)
912 return strchr(var->varstr, '=') + 1;
913 return NULL;
914}
915
916/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +0000917 * We take ownership of it.
918 * flg_export is used by:
919 * 0: do not export
920 * 1: export
921 * -1: if NAME is set, leave export status alone
922 * if NAME is not set, do not export
923 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000924static int set_local_var(char *str, int flg_export)
925{
926 struct variable *cur;
927 char *value;
928 int name_len;
929
930 value = strchr(str, '=');
931 if (!value) { /* not expected to ever happen? */
932 free(str);
933 return -1;
934 }
935
936 name_len = value - str + 1; /* including '=' */
937 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
938 while (1) {
939 if (strncmp(cur->varstr, str, name_len) != 0) {
940 if (!cur->next) {
941 /* Bail out. Note that now cur points
942 * to last var in linked list */
943 break;
944 }
945 cur = cur->next;
946 continue;
947 }
948 /* We found an existing var with this name */
949 *value = '\0';
950 if (cur->flg_read_only) {
951 bb_error_msg("%s: readonly variable", str);
952 free(str);
953 return -1;
954 }
955 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
956 unsetenv(str); /* just in case */
957 *value = '=';
958 if (strcmp(cur->varstr, str) == 0) {
959 free_and_exp:
960 free(str);
961 goto exp;
962 }
963 if (cur->max_len >= strlen(str)) {
964 /* This one is from startup env, reuse space */
965 strcpy(cur->varstr, str);
966 goto free_and_exp;
967 }
968 /* max_len == 0 signifies "malloced" var, which we can
969 * (and has to) free */
970 if (!cur->max_len)
971 free(cur->varstr);
972 cur->max_len = 0;
973 goto set_str_and_exp;
974 }
975
976 /* Not found - create next variable struct */
977 cur->next = xzalloc(sizeof(*cur));
978 cur = cur->next;
979
980 set_str_and_exp:
981 cur->varstr = str;
982 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +0000983 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000984 cur->flg_export = 1;
985 if (cur->flg_export) {
986 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
987 return putenv(cur->varstr);
988 }
989 return 0;
990}
991
992static void unset_local_var(const char *name)
993{
994 struct variable *cur;
995 struct variable *prev = prev; /* for gcc */
996 int name_len;
997
998 if (!name)
999 return;
1000 name_len = strlen(name);
1001 cur = G.top_var;
1002 while (cur) {
1003 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1004 if (cur->flg_read_only) {
1005 bb_error_msg("%s: readonly variable", name);
1006 return;
1007 }
1008 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1009 * is ro, and we cannot reach this code on the 1st pass */
1010 prev->next = cur->next;
1011 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1012 bb_unsetenv(cur->varstr);
1013 if (!cur->max_len)
1014 free(cur->varstr);
1015 free(cur);
1016 return;
1017 }
1018 prev = cur;
1019 cur = cur->next;
1020 }
1021}
1022
1023
1024/*
1025 * in_str support
1026 */
1027static int static_get(struct in_str *i)
1028{
1029 int ch = *i->p++;
1030 if (ch == '\0') return EOF;
1031 return ch;
1032}
1033
1034static int static_peek(struct in_str *i)
1035{
1036 return *i->p;
1037}
1038
1039#if ENABLE_HUSH_INTERACTIVE
1040
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001041static void cmdedit_set_initial_prompt(void)
1042{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001043 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1044 G.PS1 = getenv("PS1");
1045 if (G.PS1 == NULL)
1046 G.PS1 = "\\w \\$ ";
1047 } else
1048 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001049}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001050
1051static const char* setup_prompt_string(int promptmode)
1052{
1053 const char *prompt_str;
1054 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001055 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1056 /* Set up the prompt */
1057 if (promptmode == 0) { /* PS1 */
1058 free((char*)G.PS1);
1059 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1060 prompt_str = G.PS1;
1061 } else
1062 prompt_str = G.PS2;
1063 } else
1064 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001065 debug_printf("result '%s'\n", prompt_str);
1066 return prompt_str;
1067}
1068
1069static void get_user_input(struct in_str *i)
1070{
1071 int r;
1072 const char *prompt_str;
1073
1074 prompt_str = setup_prompt_string(i->promptmode);
1075#if ENABLE_FEATURE_EDITING
1076 /* Enable command line editing only while a command line
1077 * is actually being read */
1078 do {
1079 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1080 } while (r == 0); /* repeat if Ctrl-C */
1081 i->eof_flag = (r < 0);
1082 if (i->eof_flag) { /* EOF/error detected */
1083 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1084 G.user_input_buf[1] = '\0';
1085 }
1086#else
1087 fputs(prompt_str, stdout);
1088 fflush(stdout);
1089 G.user_input_buf[0] = r = fgetc(i->file);
1090 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1091 i->eof_flag = (r == EOF);
1092#endif
1093 i->p = G.user_input_buf;
1094}
1095
1096#endif /* INTERACTIVE */
1097
1098/* This is the magic location that prints prompts
1099 * and gets data back from the user */
1100static int file_get(struct in_str *i)
1101{
1102 int ch;
1103
1104 /* If there is data waiting, eat it up */
1105 if (i->p && *i->p) {
1106#if ENABLE_HUSH_INTERACTIVE
1107 take_cached:
1108#endif
1109 ch = *i->p++;
1110 if (i->eof_flag && !*i->p)
1111 ch = EOF;
1112 } else {
1113 /* need to double check i->file because we might be doing something
1114 * more complicated by now, like sourcing or substituting. */
1115#if ENABLE_HUSH_INTERACTIVE
1116 if (G.interactive_fd && i->promptme && i->file == stdin) {
1117 do {
1118 get_user_input(i);
1119 } while (!*i->p); /* need non-empty line */
1120 i->promptmode = 1; /* PS2 */
1121 i->promptme = 0;
1122 goto take_cached;
1123 }
1124#endif
1125 ch = fgetc(i->file);
1126 }
1127 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1128#if ENABLE_HUSH_INTERACTIVE
1129 if (ch == '\n')
1130 i->promptme = 1;
1131#endif
1132 return ch;
1133}
1134
1135/* All the callers guarantee this routine will never be
1136 * used right after a newline, so prompting is not needed.
1137 */
1138static int file_peek(struct in_str *i)
1139{
1140 int ch;
1141 if (i->p && *i->p) {
1142 if (i->eof_flag && !i->p[1])
1143 return EOF;
1144 return *i->p;
1145 }
1146 ch = fgetc(i->file);
1147 i->eof_flag = (ch == EOF);
1148 i->peek_buf[0] = ch;
1149 i->peek_buf[1] = '\0';
1150 i->p = i->peek_buf;
1151 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1152 return ch;
1153}
1154
1155static void setup_file_in_str(struct in_str *i, FILE *f)
1156{
1157 i->peek = file_peek;
1158 i->get = file_get;
1159#if ENABLE_HUSH_INTERACTIVE
1160 i->promptme = 1;
1161 i->promptmode = 0; /* PS1 */
1162#endif
1163 i->file = f;
1164 i->p = NULL;
1165}
1166
1167static void setup_string_in_str(struct in_str *i, const char *s)
1168{
1169 i->peek = static_peek;
1170 i->get = static_get;
1171#if ENABLE_HUSH_INTERACTIVE
1172 i->promptme = 1;
1173 i->promptmode = 0; /* PS1 */
1174#endif
1175 i->p = s;
1176 i->eof_flag = 0;
1177}
1178
1179
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001180/*
1181 * o_string support
1182 */
1183#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001184
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001185static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001186{
1187 o->length = 0;
1188 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001189 if (o->data)
1190 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001191}
1192
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001193static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001194{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001195 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001196 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001197}
1198
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001199static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001200{
1201 if (o->length + len > o->maxlen) {
1202 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1203 o->data = xrealloc(o->data, 1 + o->maxlen);
1204 }
1205}
1206
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001207static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001208{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001209 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1210 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001211 o->data[o->length] = ch;
1212 o->length++;
1213 o->data[o->length] = '\0';
1214}
1215
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001216static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001217{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001218 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001219 memcpy(&o->data[o->length], str, len);
1220 o->length += len;
1221 o->data[o->length] = '\0';
1222}
1223
Denis Vlasenko55789c62008-06-18 16:30:42 +00001224static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1225{
1226 while (len) {
1227 o_addchr(o, *str);
1228 if (*str++ == '\\'
1229 && (*str != '*' && *str != '?' && *str != '[')
1230 ) {
1231 o_addchr(o, '\\');
1232 }
1233 len--;
1234 }
1235}
1236
Eric Andersen25f27032001-04-26 23:22:31 +00001237/* My analysis of quoting semantics tells me that state information
1238 * is associated with a destination, not a source.
1239 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001240static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001241{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001242 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001243 char *found = strchr("*?[\\", ch);
1244 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001245 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001246 o_grow_by(o, sz);
1247 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001248 o->data[o->length] = '\\';
1249 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001250 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001251 o->data[o->length] = ch;
1252 o->length++;
1253 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001254}
1255
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001256static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001257{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001258 int sz = 1;
1259 if (o->o_quote && strchr("*?[\\", ch)) {
1260 sz++;
1261 o->data[o->length] = '\\';
1262 o->length++;
1263 }
1264 o_grow_by(o, sz);
1265 o->data[o->length] = ch;
1266 o->length++;
1267 o->data[o->length] = '\0';
1268}
1269
1270static void o_addQstr(o_string *o, const char *str, int len)
1271{
1272 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001273 o_addstr(o, str, len);
1274 return;
1275 }
1276 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001277 char ch;
1278 int sz;
1279 int ordinary_cnt = strcspn(str, "*?[\\");
1280 if (ordinary_cnt > len) /* paranoia */
1281 ordinary_cnt = len;
1282 o_addstr(o, str, ordinary_cnt);
1283 if (ordinary_cnt == len)
1284 return;
1285 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001286 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001287
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001288 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001289 sz = 1;
1290 if (ch) { /* it is necessarily one of "*?[\\" */
1291 sz++;
1292 o->data[o->length] = '\\';
1293 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001294 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001295 o_grow_by(o, sz);
1296 o->data[o->length] = ch;
1297 o->length++;
1298 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001299 }
1300}
1301
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001302/* A special kind of o_string for $VAR and `cmd` expansion.
1303 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001304 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001305 * list[i] contains an INDEX (int!) into this string data.
1306 * It means that if list[] needs to grow, data needs to be moved higher up
1307 * but list[i]'s need not be modified.
1308 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001309 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001310 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1311 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001312#if DEBUG_EXPAND || DEBUG_GLOB
1313static void debug_print_list(const char *prefix, o_string *o, int n)
1314{
1315 char **list = (char**)o->data;
1316 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1317 int i = 0;
1318 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1319 prefix, list, n, string_start, o->length, o->maxlen);
1320 while (i < n) {
1321 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1322 o->data + (int)list[i] + string_start,
1323 o->data + (int)list[i] + string_start);
1324 i++;
1325 }
1326 if (n) {
1327 const char *p = o->data + (int)list[n - 1] + string_start;
Mike Frysingerd006edb2009-03-28 12:43:53 +00001328 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001329 }
1330}
1331#else
1332#define debug_print_list(prefix, o, n) ((void)0)
1333#endif
1334
1335/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1336 * in list[n] so that it points past last stored byte so far.
1337 * It returns n+1. */
1338static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001339{
1340 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001341 int string_start;
1342 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001343
1344 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001345 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1346 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001347 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001348 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001349 /* list[n] points to string_start, make space for 16 more pointers */
1350 o->maxlen += 0x10 * sizeof(list[0]);
1351 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001352 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001353 memmove(list + n + 0x10, list + n, string_len);
1354 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001355 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001356 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001357 } else {
1358 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001359 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1360 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001361 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001362 o->has_empty_slot = 0;
1363 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001364 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001365 return n + 1;
1366}
1367
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001368/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001369static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001370{
1371 char **list = (char**)o->data;
1372 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1373
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001374 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001375}
1376
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001377/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001378 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001379static int o_glob(o_string *o, int n)
1380{
1381 glob_t globdata;
1382 int gr;
1383 char *pattern;
1384
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001385 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001386 if (!o->data)
1387 return o_save_ptr_helper(o, n);
1388 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001389 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001390 if (!glob_needed(pattern)) {
1391 literal:
1392 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001393 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001394 return o_save_ptr_helper(o, n);
1395 }
1396
1397 memset(&globdata, 0, sizeof(globdata));
1398 gr = glob(pattern, 0, NULL, &globdata);
1399 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1400 if (gr == GLOB_NOSPACE)
1401 bb_error_msg_and_die("out of memory during glob");
1402 if (gr == GLOB_NOMATCH) {
1403 globfree(&globdata);
1404 goto literal;
1405 }
1406 if (gr != 0) { /* GLOB_ABORTED ? */
1407//TODO: testcase for bad glob pattern behavior
1408 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1409 }
1410 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1411 char **argv = globdata.gl_pathv;
1412 o->length = pattern - o->data; /* "forget" pattern */
1413 while (1) {
1414 o_addstr(o, *argv, strlen(*argv) + 1);
1415 n = o_save_ptr_helper(o, n);
1416 argv++;
1417 if (!*argv)
1418 break;
1419 }
1420 }
1421 globfree(&globdata);
1422 if (DEBUG_GLOB)
1423 debug_print_list("o_glob returning", o, n);
1424 return n;
1425}
1426
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001427/* If o->o_glob == 1, glob the string so far remembered.
1428 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001429static int o_save_ptr(o_string *o, int n)
1430{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001431 if (o->o_glob) { /* if globbing is requested */
1432 /* If o->has_empty_slot, list[n] was already globbed
1433 * (if it was requested back then when it was filled)
1434 * so don't do that again! */
1435 if (!o->has_empty_slot)
1436 return o_glob(o, n); /* o_save_ptr_helper is inside */
1437 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001438 return o_save_ptr_helper(o, n);
1439}
1440
1441/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001442static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001443{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001444 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001445 int string_start;
1446
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001447 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1448 if (DEBUG_EXPAND)
1449 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001450 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001451 list = (char**)o->data;
1452 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1453 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001454 while (n) {
1455 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001456 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001457 }
1458 return list;
1459}
1460
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001461
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001462/* expand_strvec_to_strvec() takes a list of strings, expands
1463 * all variable references within and returns a pointer to
1464 * a list of expanded strings, possibly with larger number
1465 * of strings. (Think VAR="a b"; echo $VAR).
1466 * This new list is allocated as a single malloc block.
1467 * NULL-terminated list of char* pointers is at the beginning of it,
1468 * followed by strings themself.
1469 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001470
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001471/* Store given string, finalizing the word and starting new one whenever
1472 * we encounter IFS char(s). This is used for expanding variable values.
1473 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1474static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001475{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001476 while (1) {
1477 int word_len = strcspn(str, G.ifs);
1478 if (word_len) {
1479 if (output->o_quote || !output->o_glob)
1480 o_addQstr(output, str, word_len);
1481 else /* protect backslashes against globbing up :) */
1482 o_addstr_duplicate_backslash(output, str, word_len);
1483 str += word_len;
1484 }
1485 if (!*str) /* EOL - do not finalize word */
1486 break;
1487 o_addchr(output, '\0');
1488 debug_print_list("expand_on_ifs", output, n);
1489 n = o_save_ptr(output, n);
1490 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001491 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001492 debug_print_list("expand_on_ifs[1]", output, n);
1493 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001494}
1495
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001496#if ENABLE_HUSH_TICK
1497static int process_command_subs(o_string *dest,
1498 struct in_str *input, const char *subst_end);
Eric Andersen25f27032001-04-26 23:22:31 +00001499#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001500
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001501/* Expand all variable references in given string, adding words to list[]
1502 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1503 * to be filled). This routine is extremely tricky: has to deal with
1504 * variables/parameters with whitespace, $* and $@, and constructs like
1505 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1506static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001507{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001508 /* or_mask is either 0 (normal case) or 0x80
1509 * (expansion of right-hand side of assignment == 1-element expand.
1510 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001511
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001512 char first_ch, ored_ch;
1513 int i;
1514 const char *val;
1515 char *p;
1516
1517 ored_ch = 0;
1518
1519 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1520 debug_print_list("expand_vars_to_list", output, n);
1521 n = o_save_ptr(output, n);
1522 debug_print_list("expand_vars_to_list[0]", output, n);
1523
1524 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1525#if ENABLE_HUSH_TICK
1526 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001527#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001528 o_addstr(output, arg, p - arg);
1529 debug_print_list("expand_vars_to_list[1]", output, n);
1530 arg = ++p;
1531 p = strchr(p, SPECIAL_VAR_SYMBOL);
1532
1533 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1534 /* "$@" is special. Even if quoted, it can still
1535 * expand to nothing (not even an empty string) */
1536 if ((first_ch & 0x7f) != '@')
1537 ored_ch |= first_ch;
1538 val = NULL;
1539 switch (first_ch & 0x7f) {
1540 /* Highest bit in first_ch indicates that var is double-quoted */
1541 case '$': /* pid */
1542 val = utoa(G.root_pid);
1543 break;
1544 case '!': /* bg pid */
1545 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1546 break;
1547 case '?': /* exitcode */
1548 val = utoa(G.last_return_code);
1549 break;
1550 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001551 if (arg[1] != SPECIAL_VAR_SYMBOL)
1552 /* actually, it's a ${#var} */
1553 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001554 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1555 break;
1556 case '*':
1557 case '@':
1558 i = 1;
1559 if (!G.global_argv[i])
1560 break;
1561 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1562 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1563 smallint sv = output->o_quote;
1564 /* unquoted var's contents should be globbed, so don't quote */
1565 output->o_quote = 0;
1566 while (G.global_argv[i]) {
1567 n = expand_on_ifs(output, n, G.global_argv[i]);
1568 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1569 if (G.global_argv[i++][0] && G.global_argv[i]) {
1570 /* this argv[] is not empty and not last:
1571 * put terminating NUL, start new word */
1572 o_addchr(output, '\0');
1573 debug_print_list("expand_vars_to_list[2]", output, n);
1574 n = o_save_ptr(output, n);
1575 debug_print_list("expand_vars_to_list[3]", output, n);
1576 }
1577 }
1578 output->o_quote = sv;
1579 } else
1580 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1581 * and in this case should treat it like '$*' - see 'else...' below */
1582 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1583 while (1) {
1584 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1585 if (++i >= G.global_argc)
1586 break;
1587 o_addchr(output, '\0');
1588 debug_print_list("expand_vars_to_list[4]", output, n);
1589 n = o_save_ptr(output, n);
1590 }
1591 } else { /* quoted $*: add as one word */
1592 while (1) {
1593 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1594 if (!G.global_argv[++i])
1595 break;
1596 if (G.ifs[0])
1597 o_addchr(output, G.ifs[0]);
1598 }
1599 }
1600 break;
1601 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1602 /* "Empty variable", used to make "" etc to not disappear */
1603 arg++;
1604 ored_ch = 0x80;
1605 break;
1606#if ENABLE_HUSH_TICK
1607 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1608 struct in_str input;
1609 *p = '\0';
1610 arg++;
1611//TODO: can we just stuff it into "output" directly?
1612 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1613 setup_string_in_str(&input, arg);
1614 process_command_subs(&subst_result, &input, NULL);
1615 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1616 val = subst_result.data;
1617 goto store_val;
Eric Andersen25f27032001-04-26 23:22:31 +00001618 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001619#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001620 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001621 case_default: {
1622 bool exp_len = false, exp_null = false;
1623 char *var = arg, exp_save, exp_op, *exp_word;
1624 size_t exp_off = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001625 *p = '\0';
1626 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001627
1628 /* prepare for expansions */
1629 if (var[0] == '#') {
1630 /* handle length expansion ${#var} */
1631 exp_len = true;
1632 ++var;
1633 } else {
1634 /* maybe handle parameter expansion */
1635 exp_off = strcspn(var, ":-=+?");
1636 if (!var[exp_off])
1637 exp_off = 0;
1638 if (exp_off) {
1639 exp_save = var[exp_off];
1640 exp_null = exp_save == ':';
1641 exp_word = var + exp_off;
1642 if (exp_null) ++exp_word;
1643 exp_op = *exp_word++;
1644 var[exp_off] = '\0';
1645 }
1646 }
1647
1648 /* lookup the variable in question */
1649 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00001650 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001651 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001652 if (i < G.global_argc)
1653 val = G.global_argv[i];
1654 /* else val remains NULL: $N with too big N */
1655 } else
Mike Frysinger6379bb42009-03-28 18:55:03 +00001656 val = lookup_param(var);
1657
1658 /* handle any expansions */
1659 if (exp_len) {
1660 debug_printf_expand("expand: length of '%s' = ", val);
1661 val = utoa(val ? strlen(val) : 0);
1662 debug_printf_expand("%s\n", val);
1663 } else if (exp_off) {
1664 /* we need to do an expansion */
1665 int exp_test = (!val || (exp_null && !val[0]));
1666 if (exp_op == '+')
1667 exp_test = !exp_test;
1668 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1669 exp_null ? "true" : "false", exp_test);
1670 if (exp_test) {
1671 if (exp_op == '?')
1672 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1673 else
1674 val = exp_word;
1675
1676 if (exp_op == '=') {
1677 if (isdigit(var[0]) || var[0] == '#') {
1678 maybe_die(var, "special vars cannot assign in this way");
1679 val = NULL;
1680 } else {
1681 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1682 sprintf(new_var, "%s=%s", var, val);
1683 set_local_var(new_var, -1);
1684 }
1685 }
1686 }
1687 var[exp_off] = exp_save;
1688 }
1689
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001690 arg[0] = first_ch;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001691
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692#if ENABLE_HUSH_TICK
1693 store_val:
1694#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001695 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1696 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1697 if (val) {
1698 /* unquoted var's contents should be globbed, so don't quote */
1699 smallint sv = output->o_quote;
1700 output->o_quote = 0;
1701 n = expand_on_ifs(output, n, val);
1702 val = NULL;
1703 output->o_quote = sv;
1704 }
1705 } else { /* quoted $VAR, val will be appended below */
1706 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1707 }
1708 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001709 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001710 if (val) {
1711 o_addQstr(output, val, strlen(val));
1712 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001713 /* Do the check to avoid writing to a const string */
1714 if (p && *p != SPECIAL_VAR_SYMBOL)
1715 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001716
1717#if ENABLE_HUSH_TICK
1718 o_free(&subst_result);
1719#endif
1720 arg = ++p;
1721 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1722
1723 if (arg[0]) {
1724 debug_print_list("expand_vars_to_list[a]", output, n);
1725 /* this part is literal, and it was already pre-quoted
1726 * if needed (much earlier), do not use o_addQstr here! */
1727 o_addstr(output, arg, strlen(arg) + 1);
1728 debug_print_list("expand_vars_to_list[b]", output, n);
1729 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1730 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1731 ) {
1732 n--;
1733 /* allow to reuse list[n] later without re-growth */
1734 output->has_empty_slot = 1;
1735 } else {
1736 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00001737 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001738 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001739}
1740
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001741static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001742{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001743 int n;
1744 char **list;
1745 char **v;
1746 o_string output = NULL_O_STRING;
1747
1748 if (or_mask & 0x100) {
1749 output.o_quote = 1; /* protect against globbing for "$var" */
1750 /* (unquoted $var will temporarily switch it off) */
1751 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001752 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001753
1754 n = 0;
1755 v = argv;
1756 while (*v) {
1757 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1758 v++;
1759 }
1760 debug_print_list("expand_variables", &output, n);
1761
1762 /* output.data (malloced in one block) gets returned in "list" */
1763 list = o_finalize_list(&output, n);
1764 debug_print_strings("expand_variables[1]", list);
1765 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00001766}
1767
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001769{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001770 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00001771}
1772
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001773/* Used for expansion of right hand of assignments */
1774/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1775 * "v=/bin/c*" */
1776static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001777{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001778 char *argv[2], **list;
1779
1780 argv[0] = (char*)str;
1781 argv[1] = NULL;
1782 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1783 if (HUSH_DEBUG)
1784 if (!list[0] || list[1])
1785 bb_error_msg_and_die("BUG in varexp2");
1786 /* actually, just move string 2*sizeof(char*) bytes back */
1787 overlapping_strcpy((char*)list, list[0]);
1788 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1789 return (char*)list;
1790}
1791
1792/* Used for "eval" builtin */
1793static char* expand_strvec_to_string(char **argv)
1794{
1795 char **list;
1796
1797 list = expand_variables(argv, 0x80);
1798 /* Convert all NULs to spaces */
1799 if (list[0]) {
1800 int n = 1;
1801 while (list[n]) {
1802 if (HUSH_DEBUG)
1803 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1804 bb_error_msg_and_die("BUG in varexp3");
1805 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1806 n++;
1807 }
1808 }
1809 overlapping_strcpy((char*)list, list[0]);
1810 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1811 return (char*)list;
1812}
1813
1814static char **expand_assignments(char **argv, int count)
1815{
1816 int i;
1817 char **p = NULL;
1818 /* Expand assignments into one string each */
1819 for (i = 0; i < count; i++) {
1820 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1821 }
1822 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00001823}
1824
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001825
Eric Andersen25f27032001-04-26 23:22:31 +00001826/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1827 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001828static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001829{
1830 int openfd, mode;
1831 struct redir_struct *redir;
1832
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001833 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001834 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001835 /* something went wrong in the parse. Pretend it didn't happen */
1836 continue;
1837 }
Eric Andersen25f27032001-04-26 23:22:31 +00001838 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001839 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001840 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001841//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001842 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001843 openfd = open_or_warn(p, mode);
1844 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001845 if (openfd < 0) {
1846 /* this could get lost if stderr has been redirected, but
1847 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001848 return 1;
1849 }
1850 } else {
1851 openfd = redir->dup;
1852 }
1853
1854 if (openfd != redir->fd) {
1855 if (squirrel && redir->fd < 3) {
1856 squirrel[redir->fd] = dup(redir->fd);
1857 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001858 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001859 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001860 } else {
1861 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001862 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001863 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001864 }
Eric Andersen25f27032001-04-26 23:22:31 +00001865 }
1866 }
1867 return 0;
1868}
1869
1870static void restore_redirects(int squirrel[])
1871{
1872 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001873 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001874 fd = squirrel[i];
1875 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001876 /* We simply die on error */
1877 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001878 }
1879 }
1880}
1881
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001882
1883#if !defined(DEBUG_CLEAN)
1884#define free_pipe_list(head, indent) free_pipe_list(head)
1885#define free_pipe(pi, indent) free_pipe(pi)
1886#endif
1887static int free_pipe_list(struct pipe *head, int indent);
1888
1889/* return code is the exit status of the pipe */
1890static int free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001891{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001892 char **p;
1893 struct command *command;
1894 struct redir_struct *r, *rnext;
1895 int a, i, ret_code = 0;
1896
1897 if (pi->stopped_cmds > 0)
1898 return ret_code;
1899 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1900 for (i = 0; i < pi->num_cmds; i++) {
1901 command = &pi->cmds[i];
1902 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1903 if (command->argv) {
1904 for (a = 0, p = command->argv; *p; a++, p++) {
1905 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1906 }
1907 free_strings(command->argv);
1908 command->argv = NULL;
1909 } else if (command->group) {
1910 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1911 ret_code = free_pipe_list(command->group, indent+3);
1912 debug_printf_clean("%s end group\n", indenter(indent));
1913 } else {
1914 debug_printf_clean("%s (nil)\n", indenter(indent));
1915 }
1916 for (r = command->redirects; r; r = rnext) {
1917 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1918 if (r->dup == -1) {
1919 /* guard against the case >$FOO, where foo is unset or blank */
1920 if (r->rd_filename) {
1921 debug_printf_clean(" %s\n", r->rd_filename);
1922 free(r->rd_filename);
1923 r->rd_filename = NULL;
1924 }
1925 } else {
1926 debug_printf_clean("&%d\n", r->dup);
1927 }
1928 rnext = r->next;
1929 free(r);
1930 }
1931 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001932 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001933 free(pi->cmds); /* children are an array, they get freed all at once */
1934 pi->cmds = NULL;
1935#if ENABLE_HUSH_JOB
1936 free(pi->cmdtext);
1937 pi->cmdtext = NULL;
1938#endif
1939 return ret_code;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001940}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001941
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001942static int free_pipe_list(struct pipe *head, int indent)
1943{
1944 int rcode = 0; /* if list has no members */
1945 struct pipe *pi, *next;
1946
1947 for (pi = head; pi; pi = next) {
1948#if HAS_KEYWORDS
1949 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1950#endif
1951 rcode = free_pipe(pi, indent);
1952 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1953 next = pi->next;
1954 /*pi->next = NULL;*/
1955 free(pi);
1956 }
1957 return rcode;
1958}
1959
1960
1961#if !BB_MMU
1962typedef struct nommu_save_t {
1963 char **new_env;
1964 char **old_env;
1965 char **argv;
1966} nommu_save_t;
1967#else
1968#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1969 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1970#define pseudo_exec(nommu_save, command, argv_expanded) \
1971 pseudo_exec(command, argv_expanded)
1972#endif
1973
Denis Vlasenko05743d72008-02-10 12:10:08 +00001974/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001975 * Never returns.
1976 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001977 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001978 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001979static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001980static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001981{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001982 int rcode;
1983 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001984 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001985
Denis Vlasenko1359da62007-04-21 23:27:30 +00001986 /* If a variable is assigned in a forest, and nobody listens,
1987 * was it ever really set?
1988 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001989 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001990 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001991
Denis Vlasenko9504e442008-10-29 01:19:15 +00001992 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001993#if BB_MMU
1994 putenv_all(new_env);
1995 free(new_env); /* optional */
1996#else
1997 nommu_save->new_env = new_env;
1998 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001999#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002000 if (argv_expanded) {
2001 argv = argv_expanded;
2002 } else {
2003 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002004#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002005 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002006#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002007 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002008
Denis Vlasenko1359da62007-04-21 23:27:30 +00002009 /*
2010 * Check if the command matches any of the builtins.
2011 * Depending on context, this might be redundant. But it's
2012 * easier to waste a few CPU cycles than it is to figure out
2013 * if this is one of those cases.
2014 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002015 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00002016 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002017 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002018 rcode = x->function(argv);
2019 fflush(stdout);
2020 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00002021 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002022 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002023
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002024 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002025#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002026 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002027 int a = find_applet_by_name(argv[0]);
2028 if (a >= 0) {
2029 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002030 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002031// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2032 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002033 }
2034 /* re-exec ourselves with the new arguments */
2035 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00002036 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002037 /* If they called chroot or otherwise made the binary no longer
2038 * executable, fall through */
2039 }
2040 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002041#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002042
2043 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002044 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002045 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002046 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002047}
2048
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002049static int run_list(struct pipe *pi);
2050
Denis Vlasenko05743d72008-02-10 12:10:08 +00002051/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00002052 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002053static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002054static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002055{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002056 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002057 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002058
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002059 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00002060#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002061 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00002062#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00002063 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002064 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002065 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002066 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002067 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002068 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002069#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002070 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002071
2072 /* Can happen. See what bash does with ">foo" by itself. */
2073 debug_printf("trying to pseudo_exec null command\n");
2074 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002075}
2076
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002077#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002078static const char *get_cmdtext(struct pipe *pi)
2079{
2080 char **argv;
2081 char *p;
2082 int len;
2083
2084 /* This is subtle. ->cmdtext is created only on first backgrounding.
2085 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002086 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002087 if (pi->cmdtext)
2088 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002089 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002090 if (!argv || !argv[0]) {
2091 pi->cmdtext = xzalloc(1);
2092 return pi->cmdtext;
2093 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002094
2095 len = 0;
2096 do len += strlen(*argv) + 1; while (*++argv);
2097 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002098 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002099 do {
2100 len = strlen(*argv);
2101 memcpy(p, *argv, len);
2102 p += len;
2103 *p++ = ' ';
2104 } while (*++argv);
2105 p[-1] = '\0';
2106 return pi->cmdtext;
2107}
2108
Eric Andersenbafd94f2001-05-02 16:11:59 +00002109static void insert_bg_job(struct pipe *pi)
2110{
2111 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002112 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002113
2114 /* Linear search for the ID of the job to use */
2115 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002116 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002117 if (thejob->jobid >= pi->jobid)
2118 pi->jobid = thejob->jobid + 1;
2119
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002120 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002121 if (!G.job_list) {
2122 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002123 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002124 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002125 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002126 thejob->next = xmalloc(sizeof(*thejob));
2127 thejob = thejob->next;
2128 }
2129
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002130 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002131 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002132 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2133 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2134 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002135// TODO: do we really need to have so many fields which are just dead weight
2136// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002137 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002138 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002139 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002140 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002141 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002142
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002143 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002144 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002145 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2146 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002147 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002148}
2149
Eric Andersenbafd94f2001-05-02 16:11:59 +00002150static void remove_bg_job(struct pipe *pi)
2151{
2152 struct pipe *prev_pipe;
2153
Denis Vlasenko87a86552008-07-29 19:43:10 +00002154 if (pi == G.job_list) {
2155 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002156 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002157 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002158 while (prev_pipe->next != pi)
2159 prev_pipe = prev_pipe->next;
2160 prev_pipe->next = pi->next;
2161 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002162 if (G.job_list)
2163 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002164 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002165 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002166}
Eric Andersen028b65b2001-06-28 01:10:11 +00002167
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002168/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002169static void delete_finished_bg_job(struct pipe *pi)
2170{
2171 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002172 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002173 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002174 free(pi);
2175}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002176#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002177
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002178/* Check to see if any processes have exited -- if they
2179 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002180static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002181{
Eric Andersenc798b072001-06-22 06:23:03 +00002182 int attributes;
2183 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002184#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002185 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002186#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002187 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002188 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002189
Eric Andersenc798b072001-06-22 06:23:03 +00002190 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002191 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002192 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002193
Denis Vlasenko1359da62007-04-21 23:27:30 +00002194/* Do we do this right?
2195 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002196 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002197 * [3]+ Stopped sleep 20 | false
2198 * bash-3.00# echo $?
2199 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2200 */
2201
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002202//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2203//are stopped. Testcase: "cat | cat" in a script (not on command line)
2204// + killall -STOP cat
2205
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002206 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00002207// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00002208 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002209 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002210 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002211#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002212 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002213 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002214 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2215 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002216 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002217 childpid, WTERMSIG(status), WEXITSTATUS(status));
2218 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002219 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002220 childpid, WEXITSTATUS(status));
2221#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002222 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002223 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002224 for (i = 0; i < fg_pipe->num_cmds; i++) {
2225 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2226 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002227 continue;
2228 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2229 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002230 fg_pipe->cmds[i].pid = 0;
2231 fg_pipe->alive_cmds--;
2232 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002233 /* last process gives overall exitstatus */
2234 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002235 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002236 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002237 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002238 fg_pipe->cmds[i].is_stopped = 1;
2239 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002240 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002241 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2242 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2243 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002244 /* All processes in fg pipe have exited/stopped */
2245#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002246 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002247 insert_bg_job(fg_pipe);
2248#endif
2249 return rcode;
2250 }
2251 /* There are still running processes in the fg pipe */
2252 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002253 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002254 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002255 }
2256
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002257#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002258 /* We asked to wait for bg or orphaned children */
2259 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002260 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002261 for (i = 0; i < pi->num_cmds; i++) {
2262 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002263 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002264 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002265 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002266 /* Happens when shell is used as init process (init=/bin/sh) */
2267 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002268 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002269
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002270 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002271 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002272 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002273 pi->cmds[i].pid = 0;
2274 pi->alive_cmds--;
2275 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002276 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002277 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002278 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002279 }
2280 } else {
2281 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002282 pi->cmds[i].is_stopped = 1;
2283 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002284 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002285#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002286 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002287
Denis Vlasenko1359da62007-04-21 23:27:30 +00002288 /* wait found no children or failed */
2289
2290 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002291 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002292 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002293}
2294
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002295#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002296static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2297{
2298 pid_t p;
2299 int rcode = checkjobs(fg_pipe);
2300 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002301 p = getpgid(0); /* pgid of our process */
2302 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002303 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002304 return rcode;
2305}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002306#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002307
Denis Vlasenko05743d72008-02-10 12:10:08 +00002308/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00002309 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002310 *
2311 * return code is normally -1, when the caller has to wait for children
2312 * to finish to determine the exit status of the pipe. If the pipe
2313 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002314 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002315 * return value.
2316 *
2317 * The input of the pipe is always stdin, the output is always
2318 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2319 * because it tries to avoid running the command substitution in
2320 * subshell, when that is in fact necessary. The subshell process
2321 * now has its stdout directed to the input of the appropriate pipe,
2322 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00002323 *
2324 * Returns -1 only if started some children. IOW: we have to
2325 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00002326 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002327static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002328{
2329 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002330 int nextin;
2331 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002332 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002333 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002334 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00002335 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002336 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002337 /* it is not always needed, but we aim to smaller code */
2338 int squirrel[] = { -1, -1, -1 };
2339 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002340 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00002341
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002342 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002343
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002344#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00002345 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002346#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002347 pi->alive_cmds = 1;
2348 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002349
2350 /* Check if this is a simple builtin (not part of a pipe).
2351 * Builtins within pipes have to fork anyway, and are handled in
2352 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2353 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002354 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002355
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002356#if ENABLE_HUSH_FUNCTIONS
2357 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2358 /* We "execute" function definition */
2359 bb_error_msg("here we ought to remember function definition, and go on");
2360 return EXIT_SUCCESS;
2361 }
2362#endif
2363
2364 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00002365 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002366 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002367 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002368 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00002369 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002370 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002371 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00002372 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002373 }
2374
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002375 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002376 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002377
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002378 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002379 char **new_env = NULL;
2380 char **old_env = NULL;
2381
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002382 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002383 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002384 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002385 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002386 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002387 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002388 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00002389 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002390 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00002391 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002392
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002393 /* Expand the rest into (possibly) many strings each */
2394 argv_expanded = expand_strvec_to_strvec(argv + i);
2395
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002396 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002397 if (strcmp(argv_expanded[0], x->cmd) != 0)
2398 continue;
2399 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2400 debug_printf("exec with redirects only\n");
2401 setup_redirects(command, NULL);
2402 rcode = EXIT_SUCCESS;
2403 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00002404 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002405 debug_printf("builtin inline %s\n", argv_expanded[0]);
2406 /* XXX setup_redirects acts on file descriptors, not FILEs.
2407 * This is perfect for work that comes after exec().
2408 * Is it really safe for inline use? Experimentally,
2409 * things seem to work with glibc. */
2410 setup_redirects(command, squirrel);
2411 new_env = expand_assignments(argv, command->assignment_cnt);
2412 old_env = putenv_all_and_save_old(new_env);
2413 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2414 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002415#if ENABLE_FEATURE_SH_STANDALONE
2416 clean_up_and_ret:
2417#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002418 restore_redirects(squirrel);
2419 free_strings_and_unsetenv(new_env, 1);
2420 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002421 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002422 clean_up_and_ret1:
2423 free(argv_expanded);
2424 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2425 debug_printf_exec("run_pipe return %d\n", rcode);
2426 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002427 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002428#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002429 i = find_applet_by_name(argv_expanded[0]);
2430 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2431 setup_redirects(command, squirrel);
2432 save_nofork_data(&G.nofork_save);
2433 new_env = expand_assignments(argv, command->assignment_cnt);
2434 old_env = putenv_all_and_save_old(new_env);
2435 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2436 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2437 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002438 }
2439#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002440 }
2441
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002442 /* NB: argv_expanded may already be created, and that
2443 * might include `cmd` runs! Do not rerun it! We *must*
2444 * use argv_expanded if it's non-NULL */
2445
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002446 /* Disable job control signals for shell (parent) and
2447 * for initial child code after fork */
2448 set_jobctrl_sighandler(SIG_IGN);
2449
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002450 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002451 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002452 nextin = 0;
2453
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002454 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00002455#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002456 volatile nommu_save_t nommu_save;
2457 nommu_save.new_env = NULL;
2458 nommu_save.old_env = NULL;
2459 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002460#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002461 command = &(pi->cmds[i]);
2462 if (command->argv) {
2463 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002464 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002465 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002466
2467 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002468 pipefds[0] = 0;
2469 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002470 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002471 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00002472
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002473 command->pid = BB_MMU ? fork() : vfork();
2474 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00002475 if (ENABLE_HUSH_JOB)
2476 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002477#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002478 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00002479 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002480 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002481 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002482 /* Don't do pgrp restore anymore on fatal signals */
2483 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002484 pgrp = pi->pgrp;
2485 if (pgrp < 0) /* true for 1st process only */
2486 pgrp = getpid();
2487 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002488 /* We do it in *every* child, not just first,
2489 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002490 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002491 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002492 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002493#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00002494 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002495 xmove_fd(pipefds[1], 1); /* write end */
2496 if (pipefds[0] > 1)
2497 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00002498 /* Like bash, explicit redirects override pipes,
2499 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002500 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00002501
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002502 /* Restore default handlers just prior to exec */
2503 set_jobctrl_sighandler(SIG_DFL);
2504 set_misc_sighandler(SIG_DFL);
2505 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002506 /* Stores to nommu_save list of env vars putenv'ed
2507 * (NOMMU, on MMU we don't need that) */
2508 /* cast away volatility... */
2509 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002510 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002511 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002512 /* parent */
2513#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002514 /* Clean up after vforked child */
2515 free(nommu_save.argv);
2516 free_strings_and_unsetenv(nommu_save.new_env, 1);
2517 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002518#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002519 free(argv_expanded);
2520 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002521 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002522 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002523 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002524 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002525 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002526#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002527 /* Second and next children need to know pid of first one */
2528 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002529 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002530#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002531 }
Eric Andersen25f27032001-04-26 23:22:31 +00002532
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002533 if (i)
2534 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002535 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002536 close(pipefds[1]); /* write end */
2537 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002538 nextin = pipefds[0];
2539 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002540
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002541 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002542 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2543 return 1;
2544 }
2545
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002546 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002547 return -1;
2548}
2549
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002550#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002551static void debug_print_tree(struct pipe *pi, int lvl)
2552{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002553 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002554 [PIPE_SEQ] = "SEQ",
2555 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002556 [PIPE_OR ] = "OR" ,
2557 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002558 };
2559 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002560 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002561#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002562 [RES_IF ] = "IF" ,
2563 [RES_THEN ] = "THEN" ,
2564 [RES_ELIF ] = "ELIF" ,
2565 [RES_ELSE ] = "ELSE" ,
2566 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002567#endif
2568#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002569 [RES_FOR ] = "FOR" ,
2570 [RES_WHILE] = "WHILE",
2571 [RES_UNTIL] = "UNTIL",
2572 [RES_DO ] = "DO" ,
2573 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002574#endif
2575#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002576 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002577#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002578#if ENABLE_HUSH_CASE
2579 [RES_CASE ] = "CASE" ,
2580 [RES_MATCH] = "MATCH",
2581 [RES_CASEI] = "CASEI",
2582 [RES_ESAC ] = "ESAC" ,
2583#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002584 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002585 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002586 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002587 static const char *const GRPTYPE[] = {
2588 "()",
2589 "{}",
2590#if ENABLE_HUSH_FUNCTIONS
2591 "func()",
2592#endif
2593 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002594
2595 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002596
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002597 pin = 0;
2598 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002599 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2600 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002601 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002602 while (prn < pi->num_cmds) {
2603 struct command *command = &pi->cmds[prn];
2604 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002605
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002606 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2607 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002608 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002609 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002610 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002611 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002612 prn++;
2613 continue;
2614 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002615 if (argv) while (*argv) {
2616 fprintf(stderr, " '%s'", *argv);
2617 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002618 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002619 fprintf(stderr, "\n");
2620 prn++;
2621 }
2622 pi = pi->next;
2623 pin++;
2624 }
2625}
2626#endif
2627
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002628/* NB: called by pseudo_exec, and therefore must not modify any
2629 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002630static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002631{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002632#if ENABLE_HUSH_CASE
2633 char *case_word = NULL;
2634#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002635#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002636 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002637 char *for_varname = NULL;
2638 char **for_lcur = NULL;
2639 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002640#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002641 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002642 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002643#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002644 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002645#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002646 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002647#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002648 /*enum reserved_style*/ smallint rword = RES_NONE;
2649 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002650
Denis Vlasenko87a86552008-07-29 19:43:10 +00002651 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002652
Denis Vlasenko06810332007-05-21 23:30:54 +00002653#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002654 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002655 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2656 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002657 continue;
2658 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002659 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002660 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002661 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002662 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002663 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002664 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002665 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002666 continue;
2667 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002668 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2669 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002670 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002671 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002672 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002673 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002674 }
2675 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002676#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002677
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002678 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002679 * in order to return, no direct "return" statements please.
2680 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002681
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002682#if ENABLE_HUSH_JOB
2683 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2684 * We are saving state before entering outermost list ("while...done")
2685 * so that ctrl-Z will correctly background _entire_ outermost list,
2686 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002687 if (++G.run_list_level == 1 && G.interactive_fd) {
2688 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002689 /* ctrl-Z forked and we are parent; or ctrl-C.
2690 * Sighandler has longjmped us here */
2691 signal(SIGINT, SIG_IGN);
2692 signal(SIGTSTP, SIG_IGN);
2693 /* Restore level (we can be coming from deep inside
2694 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002695 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002696#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002697 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002698 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002699 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002700 }
2701#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002702 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002703 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2704 * Remember this child as background job */
2705 insert_bg_job(pi);
2706 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002707 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002708 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002709 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002710 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002711 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002712 rcode = 0;
2713 goto ret;
2714 }
2715 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002716 G.toplevel_list = pi;
2717 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002718#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002719 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002720#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002721 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002722 signal(SIGINT, handler_ctrl_c);
2723 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002724#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002725
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002726 /* Go through list of pipes, (maybe) executing them. */
2727 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002728 IF_HAS_KEYWORDS(rword = pi->res_word;)
2729 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002730 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2731 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002732#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002733 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002734 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002735 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002736 /* start of a loop: remember where loop starts */
2737 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002738 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002739 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002740#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002741 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002742 if (pi->followup == PIPE_SEQ)
2743 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002744 /* it is "<false> && CMD" or "<true> || CMD"
2745 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002746 continue;
2747 }
2748 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002749 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002750#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002751 if (cond_code) {
2752 if (rword == RES_THEN) {
2753 /* "if <false> THEN cmd": skip cmd */
2754 continue;
2755 }
2756 } else {
2757 if (rword == RES_ELSE || rword == RES_ELIF) {
2758 /* "if <true> then ... ELSE/ELIF cmd":
2759 * skip cmd and all following ones */
2760 break;
2761 }
2762 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002763#endif
2764#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002765 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002766 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002767 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002768
2769 static const char encoded_dollar_at[] ALIGN1 = {
2770 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2771 }; /* encoded representation of "$@" */
2772 static const char *const encoded_dollar_at_argv[] = {
2773 encoded_dollar_at, NULL
2774 }; /* argv list with one element: "$@" */
2775 char **vals;
2776
2777 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002778 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002779 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002780 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002781 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002782 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002783 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002784 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002785 debug_print_strings("for_list made from", vals);
2786 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002787 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002788 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002789 for_varname = pi->cmds[0].argv[0];
2790 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002791 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002792 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002793 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002794 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002795 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002796 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002797 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002798 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002799 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002800 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002801 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002802//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002803 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2804 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002805 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002806 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002807 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002808 if (rword == RES_DONE) {
2809 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002810 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002811#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002812#if ENABLE_HUSH_CASE
2813 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002814 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002815 continue;
2816 }
2817 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002818 char **argv;
2819
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002820 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2821 break;
2822 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002823 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002824 while (*argv) {
2825 char *pattern = expand_string_to_string(*argv);
2826 /* TODO: which FNM_xxx flags to use? */
2827 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2828 free(pattern);
2829 if (cond_code == 0) { /* match! we will execute this branch */
2830 free(case_word); /* make future "word)" stop */
2831 case_word = NULL;
2832 break;
2833 }
2834 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002835 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002836 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002837 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002838 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002839 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002840 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002841 }
2842#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002843 if (pi->num_cmds == 0)
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00002844 goto check_jobs_and_continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002845
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002846 /* After analyzing all keywords and conditions, we decided
2847 * to execute this pipe. NB: has to do checkjobs(NULL)
2848 * after run_pipe() to collect any background children,
2849 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002850 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002851 {
2852 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002853#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002854 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002855#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002856 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2857 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002858 /* we only ran a builtin: rcode is already known
2859 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002860#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002861 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002862 if (G.flag_break_continue) {
2863 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002864 /* we might fall into outer *loop*,
2865 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002866 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002867 G.depth_break_continue--;
2868 if (G.depth_break_continue == 0)
2869 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002870 /* else: e.g. "continue 2" should *break* once, *then* continue */
2871 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002872 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002873 goto check_jobs_and_break;
2874 /* "continue": simulate end of loop */
2875 rword = RES_DONE;
2876 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002877 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002878#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002879 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002880 /* what does bash do with attempts to background builtins? */
2881 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002882 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2883 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002884#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002885 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002886 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002887#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002888 rcode = 0; /* EXIT_SUCCESS */
2889 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002890#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002891 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002892 /* waits for completion, then fg's main shell */
2893 rcode = checkjobs_and_fg_shell(pi);
2894 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2895 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002896#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002897 { /* this one just waits for completion */
2898 rcode = checkjobs(pi);
2899 debug_printf_exec(": checkjobs returned %d\n", rcode);
2900 }
Eric Andersen25f27032001-04-26 23:22:31 +00002901 }
2902 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002903 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002904 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002905
2906 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002907#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002908 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002909 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002910#endif
2911#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002912 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002913 if (rcode) {
2914 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002915 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002916 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002917 }
2918 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002919 if (!rcode) {
2920 check_jobs_and_break:
2921 checkjobs(NULL);
2922 break;
2923 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002924 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002925#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002926 if ((rcode == 0 && pi->followup == PIPE_OR)
2927 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002928 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002929 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002930 }
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00002931
2932 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00002933 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002934 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002935
2936#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002937 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002938 /* ctrl-Z forked somewhere in the past, we are the child,
2939 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002940//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002941 exit(rcode);
2942 }
2943 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002944 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002945 signal(SIGTSTP, SIG_IGN);
2946 signal(SIGINT, SIG_IGN);
2947 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002948#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002949 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002950#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002951 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002952 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002953 free(for_list);
2954#endif
2955#if ENABLE_HUSH_CASE
2956 free(case_word);
2957#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002958 return rcode;
2959}
2960
Eric Andersen25f27032001-04-26 23:22:31 +00002961/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002962static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002963{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002964 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002965 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002966 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002967 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002968 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002969 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002970 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002971 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002972 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002973 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002974 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002975 return rcode;
2976}
2977
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002978
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002979/* Peek ahead in the in_str to find out if we have a "&n" construct,
2980 * as in "2>&1", that represents duplicating a file descriptor.
2981 * Return either -2 (syntax error), -1 (no &), or the number found.
2982 */
2983static int redirect_dup_num(struct in_str *input)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002984{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002985 int ch, d = 0, ok = 0;
2986 ch = i_peek(input);
2987 if (ch != '&') return -1;
2988
2989 i_getch(input); /* get the & */
2990 ch = i_peek(input);
2991 if (ch == '-') {
2992 i_getch(input);
2993 return -3; /* "-" represents "close me" */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002994 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002995 while (isdigit(ch)) {
2996 d = d*10 + (ch-'0');
2997 ok = 1;
2998 i_getch(input);
2999 ch = i_peek(input);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003000 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003001 if (ok) return d;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003002
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003003 bb_error_msg("ambiguous redirect");
3004 return -2;
Eric Andersen78a7c992001-05-15 16:30:25 +00003005}
3006
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003007/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00003008 * for file descriptor duplication, e.g., "2>&1".
3009 * Return code is 0 normally, 1 if a syntax error is detected in src.
3010 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003011static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00003012 struct in_str *input)
3013{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003014 struct command *command = ctx->command;
3015 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003016 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003017
3018 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003019 while (redir) {
3020 last_redir = redir;
3021 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00003022 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003023 redir = xzalloc(sizeof(struct redir_struct));
3024 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003025 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00003026 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003027 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003028 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003029 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003030 }
3031
Denis Vlasenko55789c62008-06-18 16:30:42 +00003032 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003033 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00003034
3035 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3036
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003037 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00003038 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003039 if (redir->dup == -2)
3040 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00003041 if (redir->dup != -1) {
3042 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00003043 * is legit; I postpone that to "run time"
3044 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00003045 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3046 } else {
3047 /* We do _not_ try to open the file that src points to,
3048 * since we need to return and let src be expanded first.
3049 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00003050 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00003051 ctx->pending_redirect = redir;
3052 }
3053 return 0;
3054}
3055
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003056
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003057static struct pipe *new_pipe(void)
3058{
Eric Andersen25f27032001-04-26 23:22:31 +00003059 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003060 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003061 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003062 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003063 return pi;
3064}
3065
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003066/* Command (member of a pipe) is complete. The only possible error here
3067 * is out of memory, in which case xmalloc exits. */
3068static int done_command(struct parse_context *ctx)
3069{
3070 /* The command is really already in the pipe structure, so
3071 * advance the pipe counter and make a new, null command. */
3072 struct pipe *pi = ctx->pipe;
3073 struct command *command = ctx->command;
3074
3075 if (command) {
3076 if (command->group == NULL
3077 && command->argv == NULL
3078 && command->redirects == NULL
3079 ) {
3080 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3081 return pi->num_cmds;
3082 }
3083 pi->num_cmds++;
3084 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3085 } else {
3086 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3087 }
3088
3089 /* Only real trickiness here is that the uncommitted
3090 * command structure is not counted in pi->num_cmds. */
3091 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3092 command = &pi->cmds[pi->num_cmds];
3093 memset(command, 0, sizeof(*command));
3094
3095 ctx->command = command;
3096 /* but ctx->pipe and ctx->list_head remain unchanged */
3097
3098 return pi->num_cmds; /* used only for 0/nonzero check */
3099}
3100
3101static void done_pipe(struct parse_context *ctx, pipe_style type)
3102{
3103 int not_null;
3104
3105 debug_printf_parse("done_pipe entered, followup %d\n", type);
3106 /* Close previous command */
3107 not_null = done_command(ctx);
3108 ctx->pipe->followup = type;
3109 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3110 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3111 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3112
3113 /* Without this check, even just <enter> on command line generates
3114 * tree of three NOPs (!). Which is harmless but annoying.
3115 * IOW: it is safe to do it unconditionally.
3116 * RES_NONE case is for "for a in; do ..." (empty IN set)
3117 * to work, possibly other cases too. */
3118 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3119 struct pipe *new_p;
3120 debug_printf_parse("done_pipe: adding new pipe: "
3121 "not_null:%d ctx->ctx_res_w:%d\n",
3122 not_null, ctx->ctx_res_w);
3123 new_p = new_pipe();
3124 ctx->pipe->next = new_p;
3125 ctx->pipe = new_p;
3126 ctx->command = NULL; /* needed! */
3127 /* RES_THEN, RES_DO etc are "sticky" -
3128 * they remain set for commands inside if/while.
3129 * This is used to control execution.
3130 * RES_FOR and RES_IN are NOT sticky (needed to support
3131 * cases where variable or value happens to match a keyword):
3132 */
3133#if ENABLE_HUSH_LOOPS
3134 if (ctx->ctx_res_w == RES_FOR
3135 || ctx->ctx_res_w == RES_IN)
3136 ctx->ctx_res_w = RES_NONE;
3137#endif
3138#if ENABLE_HUSH_CASE
3139 if (ctx->ctx_res_w == RES_MATCH)
3140 ctx->ctx_res_w = RES_CASEI;
3141#endif
3142 /* Create the memory for command, roughly:
3143 * ctx->pipe->cmds = new struct command;
3144 * ctx->command = &ctx->pipe->cmds[0];
3145 */
3146 done_command(ctx);
3147 }
3148 debug_printf_parse("done_pipe return\n");
3149}
3150
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003151static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003152{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003153 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003154 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003155 /* Create the memory for command, roughly:
3156 * ctx->pipe->cmds = new struct command;
3157 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003158 */
3159 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003160}
3161
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003162
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003163/* If a reserved word is found and processed, parse context is modified
3164 * and 1 is returned.
3165 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003166 * case, function, and select are obnoxious, save those for later.
3167 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003168#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003169struct reserved_combo {
3170 char literal[6];
3171 unsigned char res;
3172 unsigned char assignment_flag;
3173 int flag;
3174};
3175enum {
3176 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003177#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003178 FLAG_IF = (1 << RES_IF ),
3179 FLAG_THEN = (1 << RES_THEN ),
3180 FLAG_ELIF = (1 << RES_ELIF ),
3181 FLAG_ELSE = (1 << RES_ELSE ),
3182 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003183#endif
3184#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003185 FLAG_FOR = (1 << RES_FOR ),
3186 FLAG_WHILE = (1 << RES_WHILE),
3187 FLAG_UNTIL = (1 << RES_UNTIL),
3188 FLAG_DO = (1 << RES_DO ),
3189 FLAG_DONE = (1 << RES_DONE ),
3190 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003191#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003192#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003193 FLAG_MATCH = (1 << RES_MATCH),
3194 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003195#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003196 FLAG_START = (1 << RES_XXXX ),
3197};
3198
3199static const struct reserved_combo* match_reserved_word(o_string *word)
3200{
Eric Andersen25f27032001-04-26 23:22:31 +00003201 /* Mostly a list of accepted follow-up reserved words.
3202 * FLAG_END means we are done with the sequence, and are ready
3203 * to turn the compound list into a command.
3204 * FLAG_START means the word must start a new compound list.
3205 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003206 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003207#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003208 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3209 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3210 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3211 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3212 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3213 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003214#endif
3215#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003216 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3217 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3218 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3219 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3220 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3221 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003222#endif
3223#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003224 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3225 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003226#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003227 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003228 const struct reserved_combo *r;
3229
3230 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3231 if (strcmp(word->data, r->literal) == 0)
3232 return r;
3233 }
3234 return NULL;
3235}
3236static int reserved_word(o_string *word, struct parse_context *ctx)
3237{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003238#if ENABLE_HUSH_CASE
3239 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003240 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003241 };
3242#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003243 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003244
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003245 r = match_reserved_word(word);
3246 if (!r)
3247 return 0;
3248
3249 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003250#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003251 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3252 /* "case word IN ..." - IN part starts first match part */
3253 r = &reserved_match;
3254 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003255#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003256 if (r->flag == 0) { /* '!' */
3257 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003258 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003259 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003260 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003261 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003262 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003263 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003264 if (r->flag & FLAG_START) {
3265 struct parse_context *new;
3266 debug_printf("push stack\n");
3267 new = xmalloc(sizeof(*new));
3268 *new = *ctx; /* physical copy */
3269 initialize_context(ctx);
3270 ctx->stack = new;
3271 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3272 syntax(NULL);
3273 ctx->ctx_res_w = RES_SNTX;
3274 return 1;
3275 }
3276 ctx->ctx_res_w = r->res;
3277 ctx->old_flag = r->flag;
3278 if (ctx->old_flag & FLAG_END) {
3279 struct parse_context *old;
3280 debug_printf("pop stack\n");
3281 done_pipe(ctx, PIPE_SEQ);
3282 old = ctx->stack;
3283 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003284 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003285 *ctx = *old; /* physical copy */
3286 free(old);
3287 }
3288 word->o_assignment = r->assignment_flag;
3289 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003290}
Denis Vlasenko06810332007-05-21 23:30:54 +00003291#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003292
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003293//TODO: many, many callers don't check error from done_word()
3294
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003295/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003296 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003297static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003298{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003299 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003300
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003301 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003302 if (word->length == 0 && word->nonnull == 0) {
3303 debug_printf_parse("done_word return 0: true null, ignored\n");
3304 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003305 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003306 /* If this word wasn't an assignment, next ones definitely
3307 * can't be assignments. Even if they look like ones. */
3308 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3309 && word->o_assignment != WORD_IS_KEYWORD
3310 ) {
3311 word->o_assignment = NOT_ASSIGNMENT;
3312 } else {
3313 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003314 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003315 word->o_assignment = MAYBE_ASSIGNMENT;
3316 }
3317
Eric Andersen25f27032001-04-26 23:22:31 +00003318 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003319 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3320 * only if run as "bash", not "sh" */
3321 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003322 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003323 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003324 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003325 /* "{ echo foo; } echo bar" - bad */
3326 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003327 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003328 syntax(NULL);
3329 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3330 return 1;
3331 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003332#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003333#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003334 if (ctx->ctx_dsemicolon
3335 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3336 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003337 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003338 /* ctx->ctx_res_w = RES_MATCH; */
3339 ctx->ctx_dsemicolon = 0;
3340 } else
3341#endif
3342
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003343 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003344#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003345 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3346 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003347#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003348 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003349 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3350 if (reserved_word(word, ctx)) {
3351 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003352 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3353 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003354 }
Eric Andersen25f27032001-04-26 23:22:31 +00003355 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003356#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003357 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003358 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3359 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003360 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003361 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003362 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003363 char *p = word->data;
3364 while (p[0] == SPECIAL_VAR_SYMBOL
3365 && (p[1] & 0x7f) == '@'
3366 && p[2] == SPECIAL_VAR_SYMBOL
3367 ) {
3368 p += 3;
3369 }
3370 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003371 /* saw no "$@", or not only "$@" but some
3372 * real text is there too */
3373 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003374 * e.g. "", $empty"" etc to not disappear */
3375 o_addchr(word, SPECIAL_VAR_SYMBOL);
3376 o_addchr(word, SPECIAL_VAR_SYMBOL);
3377 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003378 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003379 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003380 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003381 }
Eric Andersen25f27032001-04-26 23:22:31 +00003382
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003383 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003384 ctx->pending_redirect = NULL;
3385
Denis Vlasenko06810332007-05-21 23:30:54 +00003386#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003387 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003388 /* NB: basically, this makes hush see "for v in ..." syntax as if
3389 * as it is "for v; in ...". FOR and IN become two pipe structs
3390 * in parse tree. */
3391 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003392//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003393 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003394 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003395#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003396#if ENABLE_HUSH_CASE
3397 /* Force CASE to have just one word */
3398 if (ctx->ctx_res_w == RES_CASE) {
3399 done_pipe(ctx, PIPE_SEQ);
3400 }
3401#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003402 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003403 return 0;
3404}
3405
Eric Andersen25f27032001-04-26 23:22:31 +00003406/* If a redirect is immediately preceded by a number, that number is
3407 * supposed to tell which file descriptor to redirect. This routine
3408 * looks for such preceding numbers. In an ideal world this routine
3409 * needs to handle all the following classes of redirects...
3410 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3411 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3412 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3413 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3414 * A -1 output from this program means no valid number was found, so the
3415 * caller should use the appropriate default for this redirection.
3416 */
3417static int redirect_opt_num(o_string *o)
3418{
3419 int num;
3420
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003421 if (o->length == 0)
3422 return -1;
3423 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003424 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003425 return -1;
3426 }
3427 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003428 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003429 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003430 return num;
3431}
3432
Mike Frysingerddbee972009-03-22 22:48:41 +00003433static int parse_stream(o_string *dest, struct parse_context *ctx,
3434 struct in_str *input0, const char *end_trigger);
3435
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003436#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003437static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003438{
3439 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003440 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003441
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003442 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003443/* *** NOMMU WARNING *** */
3444/* By using vfork here, we suspend parent till child exits or execs.
3445 * If child will not do it before it fills the pipe, it can block forever
3446 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003447 * Try this script:
3448 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3449 * huge=`cat TESTFILE` # will block here forever
3450 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003451 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003452 pid = BB_MMU ? fork() : vfork();
3453 if (pid < 0)
3454 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003455 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003456 if (ENABLE_HUSH_JOB)
3457 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003458 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003459 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003460 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003461#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003462 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003463#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003464 /* Process substitution is not considered to be usual
3465 * 'command execution'.
3466 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3467 /* Not needed, we are relying on it being disabled
3468 * everywhere outside actual command execution. */
3469 /*set_jobctrl_sighandler(SIG_IGN);*/
3470 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003471 /* Freeing 'head' here would break NOMMU. */
3472 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003473 }
Eric Andersen25f27032001-04-26 23:22:31 +00003474 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003475 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003476 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003477 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003478}
3479
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003480/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003481static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003482 struct in_str *input,
3483 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003484{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003485 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003486 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003487 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003488 FILE *p;
3489 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003490
Eric Andersen25f27032001-04-26 23:22:31 +00003491 initialize_context(&inner);
3492
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003493 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003494 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003495 if (retcode != 0)
3496 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003497 done_word(&result, &inner);
3498 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003499 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003500
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003501 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003502 if (p == NULL)
3503 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003504 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003505 setup_file_in_str(&pipe_str, p);
3506
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003507 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003508 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003509 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003510 if (ch == '\n') {
3511 eol_cnt++;
3512 continue;
3513 }
3514 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003515 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003516 eol_cnt--;
3517 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003518 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003519 }
3520
3521 debug_printf("done reading from pipe, pclose()ing\n");
3522 /* This is the step that wait()s for the child. Should be pretty
3523 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003524 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003525 * at the same time. That would be a lot of work, and contrary
3526 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003527 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003528 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003529 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003530 return retcode;
3531}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003532#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003533
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003534static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003535 struct in_str *input, int ch)
3536{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003537 /* dest contains characters seen prior to ( or {.
3538 * Typically it's empty, but for functions defs,
3539 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003540 int rcode;
3541 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003542 struct parse_context sub;
3543 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003544
3545 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003546#if ENABLE_HUSH_FUNCTIONS
3547 if (ch == 'F') { /* function definition? */
3548 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3549 //command->fname = dest->data;
3550 command->grp_type = GRP_FUNCTION;
3551//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3552 memset(dest, 0, sizeof(*dest));
3553 }
3554#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003555 if (command->argv /* word [word](... */
3556 || dest->length /* word(... */
3557 || dest->nonnull /* ""(... */
3558 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003559 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003560 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3561 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003562 }
3563 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003564 endch = "}";
3565 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003566 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003567 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003568 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003569 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003570 if (rcode == 0) {
3571 done_word(dest, &sub); /* finish off the final word in the subcontext */
3572 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003573 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003574 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003575 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003576 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003577 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003578}
3579
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003580#if ENABLE_HUSH_TICK
3581/* Subroutines for copying $(...) and `...` things */
3582static void add_till_backquote(o_string *dest, struct in_str *input);
3583/* '...' */
3584static void add_till_single_quote(o_string *dest, struct in_str *input)
3585{
3586 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003587 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003588 if (ch == EOF)
3589 break;
3590 if (ch == '\'')
3591 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003592 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003593 }
3594}
3595/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3596static void add_till_double_quote(o_string *dest, struct in_str *input)
3597{
3598 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003599 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003600 if (ch == '"')
3601 break;
3602 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003603 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003604 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003605 }
3606 if (ch == EOF)
3607 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003608 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003609 if (ch == '`') {
3610 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003611 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003612 continue;
3613 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003614 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003615 }
3616}
3617/* Process `cmd` - copy contents until "`" is seen. Complicated by
3618 * \` quoting.
3619 * "Within the backquoted style of command substitution, backslash
3620 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3621 * The search for the matching backquote shall be satisfied by the first
3622 * backquote found without a preceding backslash; during this search,
3623 * if a non-escaped backquote is encountered within a shell comment,
3624 * a here-document, an embedded command substitution of the $(command)
3625 * form, or a quoted string, undefined results occur. A single-quoted
3626 * or double-quoted string that begins, but does not end, within the
3627 * "`...`" sequence produces undefined results."
3628 * Example Output
3629 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3630 */
3631static void add_till_backquote(o_string *dest, struct in_str *input)
3632{
3633 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003634 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003635 if (ch == '`')
3636 break;
3637 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003638 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003639 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003640 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003641 ch = ch2;
3642 }
3643 if (ch == EOF)
3644 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003645 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003646 }
3647}
3648/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3649 * quoting and nested ()s.
3650 * "With the $(command) style of command substitution, all characters
3651 * following the open parenthesis to the matching closing parenthesis
3652 * constitute the command. Any valid shell script can be used for command,
3653 * except a script consisting solely of redirections which produces
3654 * unspecified results."
3655 * Example Output
3656 * echo $(echo '(TEST)' BEST) (TEST) BEST
3657 * echo $(echo 'TEST)' BEST) TEST) BEST
3658 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3659 */
3660static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3661{
3662 int count = 0;
3663 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003664 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003665 if (ch == EOF)
3666 break;
3667 if (ch == '(')
3668 count++;
3669 if (ch == ')')
3670 if (--count < 0)
3671 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003672 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003673 if (ch == '\'') {
3674 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003675 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003676 continue;
3677 }
3678 if (ch == '"') {
3679 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003680 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003681 continue;
3682 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003683 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3684 ch = i_getch(input);
3685 if (ch == EOF)
3686 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003687 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003688 continue;
3689 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003690 }
3691}
3692#endif /* ENABLE_HUSH_TICK */
3693
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003694/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003695static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003696{
Mike Frysinger6379bb42009-03-28 18:55:03 +00003697 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003698 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003699 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003700
3701 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003702 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003703 i_getch(input);
3704 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003705 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003706 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003707 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003708 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003709 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003710 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003711 if (!isalnum(ch) && ch != '_')
3712 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003713 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003714 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003715 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003716 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003717 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003718 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003719 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003720 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003721 o_addchr(dest, ch | quote_mask);
3722 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003723 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003724 case '$': /* pid */
3725 case '!': /* last bg pid */
3726 case '?': /* last exit code */
3727 case '#': /* number of args */
3728 case '*': /* args */
3729 case '@': /* args */
3730 goto make_one_char_var;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003731 case '{': {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003732 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003733
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003734 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3735 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003736 /* XXX maybe someone will try to escape the '}' */
Mike Frysinger6379bb42009-03-28 18:55:03 +00003737 expansion = 0;
3738 first_char = true;
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003739 all_digits = false;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003740 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003741 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003742 if (ch == '}')
3743 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003744
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003745 if (first_char) {
3746 if (ch == '#')
3747 /* ${#var}: length of var contents */
3748 goto char_ok;
3749 else if (isdigit(ch)) {
3750 all_digits = true;
3751 goto char_ok;
3752 }
3753 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00003754
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003755 if (expansion < 2 &&
3756 ((all_digits && !isdigit(ch)) ||
3757 (!all_digits && !isalnum(ch) && ch != '_')))
3758 {
Mike Frysinger6379bb42009-03-28 18:55:03 +00003759 /* handle parameter expansions
3760 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3761 */
3762 if (first_char)
3763 goto case_default;
3764 switch (ch) {
3765 case ':': /* null modifier */
3766 if (expansion == 0) {
3767 debug_printf_parse(": null modifier\n");
3768 ++expansion;
3769 break;
3770 }
3771 goto case_default;
3772
3773#if 0 /* not implemented yet :( */
3774 case '#': /* remove prefix */
3775 case '%': /* remove suffix */
3776 if (expansion == 0) {
3777 debug_printf_parse(": remove suffix/prefix\n");
3778 expansion = 2;
3779 break;
3780 }
3781 goto case_default;
3782#endif
3783
3784 case '-': /* default value */
3785 case '=': /* assign default */
3786 case '+': /* alternative */
3787 case '?': /* error indicate */
3788 debug_printf_parse(": parameter expansion\n");
3789 expansion = 2;
3790 break;
3791
3792 default:
3793 case_default:
3794 syntax("unterminated ${name}");
3795 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3796 return 1;
3797 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003798 }
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003799
3800 char_ok:
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003801 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003802 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003803 quote_mask = 0;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003804 first_char = false;
Eric Andersen25f27032001-04-26 23:22:31 +00003805 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003806 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003807 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003808 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003809#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003810 case '(': {
3811 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003812 i_getch(input);
3813 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3814 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003815 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003816 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003817 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003818 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003819 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003820#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003821 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003822 i_getch(input);
3823 ch = i_peek(input);
3824 if (isalnum(ch)) { /* it's $_name or $_123 */
3825 ch = '_';
3826 goto make_var;
3827 }
3828 /* else: it's $_ */
3829 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003830 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003831 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003832 return 1;
3833 break;
3834 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003835 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003836 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003837 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003838 return 0;
3839}
3840
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003841/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003842 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3843 * Return code is 0 if end_trigger char is met,
3844 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003845 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003846static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003847 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003848{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003849 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003850 int redir_fd;
3851 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003852 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003853 int next;
3854
Denis Vlasenkoff097622007-10-01 10:00:45 +00003855 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003856 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003857 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003858
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003859 debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003860
Denis Vlasenko1a735862007-05-23 00:32:25 +00003861 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003862 m = CHAR_IFS;
3863 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003864 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003865 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003866 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003867 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003868 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003869 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003870 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003871 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003872 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003873 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003874 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003875 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003876 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003877 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003878 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3879 return 1;
3880 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003881 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003882 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3883 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003884 && ch == '='
3885 && is_assignment(dest->data)
3886 ) {
3887 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3888 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003889 continue;
3890 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003891 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003892 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003893 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003894 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003895 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003896 if (ch == EOF)
3897 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003898 /* If we aren't performing a substitution, treat
3899 * a newline as a command separator.
3900 * [why we don't handle it exactly like ';'? --vda] */
3901 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003902#if ENABLE_HUSH_CASE
3903 /* "case ... in <newline> word) ..." -
3904 * newlines are ignored (but ';' wouldn't be) */
3905 if (dest->length == 0 // && argv[0] == NULL
3906 && ctx->ctx_res_w == RES_MATCH
3907 ) {
3908 continue;
3909 }
3910#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003911 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003912 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003913 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003914 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003915 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003916 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003917 /* Special case: (...word) makes last word terminate,
3918 * as if ';' is seen */
3919 if (ch == ')') {
3920 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003921//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003922 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003923 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003924 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003925 if (!HAS_KEYWORDS
3926 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3927 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003928 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3929 return 0;
3930 }
3931 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003932 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003933 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003934 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003935
3936 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3937 /* ch is a special char and thus this word
3938 * cannot be an assignment: */
3939 dest->o_assignment = NOT_ASSIGNMENT;
3940 }
3941
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003942 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003943 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003944 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003945 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003946 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003947 if (ch == EOF || ch == '\n')
3948 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003949 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003950 }
Eric Andersen25f27032001-04-26 23:22:31 +00003951 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003952 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003953 }
3954 break;
3955 case '\\':
3956 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003957 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003958 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003959 return 1;
3960 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003961 /* bash:
3962 * "The backslash retains its special meaning [in "..."]
3963 * only when followed by one of the following characters:
3964 * $, `, ", \, or <newline>. A double quote may be quoted
3965 * within double quotes by preceding it with a backslash.
3966 * If enabled, history expansion will be performed unless
3967 * an ! appearing in double quotes is escaped using
3968 * a backslash. The backslash preceding the ! is not removed."
3969 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003970 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003971 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003972 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003973 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003974 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003975 }
3976 } else {
3977 o_addchr(dest, '\\');
3978 o_addchr(dest, i_getch(input));
3979 }
Eric Andersen25f27032001-04-26 23:22:31 +00003980 break;
3981 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003982 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003983 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3984 return 1;
3985 }
Eric Andersen25f27032001-04-26 23:22:31 +00003986 break;
3987 case '\'':
3988 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003989 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003990 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003991 if (ch == EOF) {
3992 syntax("unterminated '");
3993 debug_printf_parse("parse_stream return 1: unterminated '\n");
3994 return 1;
3995 }
3996 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003997 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003998 if (dest->o_assignment == NOT_ASSIGNMENT)
3999 o_addqchr(dest, ch);
4000 else
4001 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004002 }
Eric Andersen25f27032001-04-26 23:22:31 +00004003 break;
4004 case '"':
4005 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004006 shadow_quote ^= 1; /* invert */
4007 if (dest->o_assignment == NOT_ASSIGNMENT)
4008 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004009 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004010#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004011 case '`': {
4012 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004014 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004015 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004016 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00004017 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004018 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004019 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004020#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004021 case '>':
4022 redir_fd = redirect_opt_num(dest);
4023 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004024 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00004025 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004026 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004027 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004028 }
4029#if 0
4030 else if (next == '(') {
4031 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004032 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004033 return 1;
4034 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004035#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004036 setup_redirect(ctx, redir_fd, redir_style, input);
4037 break;
4038 case '<':
4039 redir_fd = redirect_opt_num(dest);
4040 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004041 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00004042 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004043 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004044 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004045 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004046 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004047 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004048 }
4049#if 0
4050 else if (next == '(') {
4051 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004052 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004053 return 1;
4054 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004055#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004056 setup_redirect(ctx, redir_fd, redir_style, input);
4057 break;
4058 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004059#if ENABLE_HUSH_CASE
4060 case_semi:
4061#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004062 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004063 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004064#if ENABLE_HUSH_CASE
4065 /* Eat multiple semicolons, detect
4066 * whether it means something special */
4067 while (1) {
4068 ch = i_peek(input);
4069 if (ch != ';')
4070 break;
4071 i_getch(input);
4072 if (ctx->ctx_res_w == RES_CASEI) {
4073 ctx->ctx_dsemicolon = 1;
4074 ctx->ctx_res_w = RES_MATCH;
4075 break;
4076 }
4077 }
4078#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004079 new_cmd:
4080 /* We just finished a cmd. New one may start
4081 * with an assignment */
4082 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004083 break;
4084 case '&':
4085 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004086 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004087 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004088 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004089 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004090 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004091 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004092 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004093 case '|':
4094 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004095#if ENABLE_HUSH_CASE
4096 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004097 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004098#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004099 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004100 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004101 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004102 } else {
4103 /* we could pick up a file descriptor choice here
4104 * with redirect_opt_num(), but bash doesn't do it.
4105 * "echo foo 2| cat" yields "foo 2". */
4106 done_command(ctx);
4107 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004108 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004109 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004110#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004111 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004112 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004113 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004114 && dest->length == 0 /* not word(... */
4115 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004116 ) {
4117 continue;
4118 }
4119#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004120#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004121 if (dest->length != 0 /* not just () but word() */
4122 && dest->nonnull == 0 /* not a"b"c() */
4123 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004124//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004125 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004126 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004127 ) {
4128 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004129 i_getch(input);
4130 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004131//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004132 ch = i_getch(input);
4133 } while (ch == ' ' || ch == '\n');
4134 if (ch != '{') {
4135 syntax("was expecting {");
4136 debug_printf_parse("parse_stream return 1\n");
4137 return 1;
4138 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004139 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004140 }
4141#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004142 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004143 if (parse_group(dest, ctx, input, ch) != 0) {
4144 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004145 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004146 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004147 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004148 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004149#if ENABLE_HUSH_CASE
4150 if (ctx->ctx_res_w == RES_MATCH)
4151 goto case_semi;
4152#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004153 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004154 /* proper use of this character is caught by end_trigger:
4155 * if we see {, we call parse_group(..., end_trigger='}')
4156 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004157 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004158 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004159 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004160 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004161 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004162 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004163 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004164 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004165 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004166 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004167 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004168 return 0;
4169}
4170
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004171static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004172{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004173 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004174 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004175}
4176
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004177static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004178{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004179 G.ifs = getenv("IFS");
4180 if (G.ifs == NULL)
4181 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004182 /* Precompute a list of 'flow through' behavior so it can be treated
4183 * quickly up front. Computation is necessary because of IFS.
4184 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004185 * The charmap[] array only really needs two bits each,
4186 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004187 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004188 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004189#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004190 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004191#else
4192 set_in_charmap("\\$\"", CHAR_SPECIAL);
4193#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004194 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004195 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004196}
4197
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004198/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004199 * from builtin_source() and builtin_eval() */
4200static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004201{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004202 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004203 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004204 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004205
Eric Andersen25f27032001-04-26 23:22:31 +00004206 do {
4207 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004208 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004209#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004210 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004211#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004212 /* We will stop & execute after each ';' or '\n'.
4213 * Example: "sleep 9999; echo TEST" + ctrl-C:
4214 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004215 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004216 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004217#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004218 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004219 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004220 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004221#endif
4222 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004223 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004224 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004225 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004226 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4227 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004228 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004229 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004230#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004231 if (ctx.old_flag != 0) {
4232 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004233 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004234 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004235#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004236 /*temp.nonnull = 0; - o_free does it below */
4237 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004238 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004239 /* Discard all unprocessed line input, force prompt on */
4240 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004241#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004242 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004243#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004244 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004245 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004246 /* loop on syntax errors, return on EOF: */
4247 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004248 return 0;
4249}
4250
Denis Vlasenko170435c2007-05-23 13:01:10 +00004251static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004252{
4253 struct in_str input;
4254 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004255 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004256}
4257
Denis Vlasenko170435c2007-05-23 13:01:10 +00004258static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004259{
4260 int rcode;
4261 struct in_str input;
4262 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004263 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004264 return rcode;
4265}
4266
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004267#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004268/* Make sure we have a controlling tty. If we get started under a job
4269 * aware app (like bash for example), make sure we are now in charge so
4270 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004271static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004272{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004273 pid_t shell_pgrp;
4274
Denis Vlasenko87a86552008-07-29 19:43:10 +00004275 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004276 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004277
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004278 /* If we were ran as 'hush &',
4279 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004280 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004281 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004282 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004283 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004284 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004285
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004286 /* Ignore job-control and misc signals. */
4287 set_jobctrl_sighandler(SIG_IGN);
4288 set_misc_sighandler(SIG_IGN);
4289//huh? signal(SIGCHLD, SIG_IGN);
4290
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004291 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004292 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004293
4294 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004295 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004296 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004297 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004298}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004299#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004300
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004301
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004302int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004303int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004304{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004305 static const struct variable const_shell_ver = {
4306 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004307 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004308 .max_len = 1, /* 0 can provoke free(name) */
4309 .flg_export = 1,
4310 .flg_read_only = 1,
4311 };
4312
Eric Andersen25f27032001-04-26 23:22:31 +00004313 int opt;
4314 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004315 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004316 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004317
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004318 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004319
Denis Vlasenko87a86552008-07-29 19:43:10 +00004320 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004321
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004322 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004323 G.shell_ver = const_shell_ver; /* copying struct here */
4324 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004325 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004326 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4327 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004328 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004329 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004330 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004331 if (e) while (*e) {
4332 char *value = strchr(*e, '=');
4333 if (value) { /* paranoia */
4334 cur_var->next = xzalloc(sizeof(*cur_var));
4335 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004336 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004337 cur_var->max_len = strlen(*e);
4338 cur_var->flg_export = 1;
4339 }
4340 e++;
4341 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004342 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004343 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004344
Denis Vlasenko38f63192007-01-22 09:03:07 +00004345#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004346 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004347#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004348 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004349 G.global_argc = argc;
4350 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004351 /* Initialize some more globals to non-zero values */
4352 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004353#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00004354 if (ENABLE_FEATURE_EDITING)
4355 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004356 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004357#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004358
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004359 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004360 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004361
4362 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004363 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004364 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004365 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004366 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004367 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004368 fclose(input);
4369 }
Eric Andersen25f27032001-04-26 23:22:31 +00004370 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004371 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004372
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004373 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4374 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00004375 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004376 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004377 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00004378 if (!argv[optind]) {
4379 /* -c 'script' (no params): prevent empty $0 */
4380 *--G.global_argv = argv[0];
4381 optind--;
4382 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004383 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004384 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004385 goto final_return;
4386 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004387 /* Well, we cannot just declare interactiveness,
4388 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004389 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004390 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004391 case 's':
4392 /* "-s" means "read from stdin", but this is how we always
4393 * operate, so simply do nothing here. */
4394 break;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004395 case 'n':
4396 case 'x':
4397 if (!builtin_set_mode('-', opt))
4398 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004399 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004400#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004401 fprintf(stderr, "Usage: sh [FILE]...\n"
4402 " or: sh -c command [args]...\n\n");
4403 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004404#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004405 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004406#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004407 }
4408 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004409#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004410 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004411 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004412 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004413 * no arguments remaining or the -s flag given
4414 * standard input is a terminal
4415 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004416 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004417 if (argv[optind] == NULL && input == stdin
4418 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4419 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004420 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4421 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4422 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004423 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004424 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4425 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004426 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004427 G.interactive_fd = dup(STDIN_FILENO);
4428 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004429 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004430 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004431 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004432 // TODO: track & disallow any attempts of user
4433 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004434 }
Eric Andersen25f27032001-04-26 23:22:31 +00004435 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004436 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4437 if (G.interactive_fd) {
4438 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004439 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004440 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004441 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004442 * (we reset die_sleep = 0 whereever we [v]fork) */
4443 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004444 if (setjmp(die_jmp)) {
4445 /* xfunc has failed! die die die */
4446 hush_exit(xfunc_error_retval);
4447 }
Eric Andersenada18ff2001-05-21 16:18:22 +00004448 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004449#elif ENABLE_HUSH_INTERACTIVE
4450/* no job control compiled, only prompt/line editing */
4451 if (argv[optind] == NULL && input == stdin
4452 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4453 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004454 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4455 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004456 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004457 G.interactive_fd = dup(STDIN_FILENO);
4458 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004459 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004460 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004461 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004462 if (G.interactive_fd) {
4463 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004464 set_misc_sighandler(SIG_IGN);
4465 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004466 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004467#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004468
Denis Vlasenko701ac182009-03-28 19:22:08 +00004469#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4470 if (G.interactive_fd) {
Mike Frysingerb2705e12009-03-23 08:44:02 +00004471 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4472 printf("Enter 'help' for a list of built-in commands.\n\n");
4473 }
Denis Vlasenko701ac182009-03-28 19:22:08 +00004474#endif
Mike Frysingerb2705e12009-03-23 08:44:02 +00004475
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004476 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004477 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004478 } else {
4479 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004480 G.global_argv = argv + optind;
4481 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004482 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004483 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004484 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004485 }
Eric Andersen25f27032001-04-26 23:22:31 +00004486
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004487 final_return:
4488
Denis Vlasenko38f63192007-01-22 09:03:07 +00004489#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004490 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004491 if (G.cwd != bb_msg_unknown)
4492 free((char*)G.cwd);
4493 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004494 while (cur_var) {
4495 struct variable *tmp = cur_var;
4496 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004497 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004498 cur_var = cur_var->next;
4499 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004500 }
Eric Andersen25f27032001-04-26 23:22:31 +00004501#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004502 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004503}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004504
4505
4506#if ENABLE_LASH
4507int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4508int lash_main(int argc, char **argv)
4509{
4510 //bb_error_msg("lash is deprecated, please use hush instead");
4511 return hush_main(argc, argv);
4512}
4513#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004514
4515
4516/*
4517 * Built-ins
4518 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004519static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004520{
4521 return 0;
4522}
4523
4524static int builtin_test(char **argv)
4525{
4526 int argc = 0;
4527 while (*argv) {
4528 argc++;
4529 argv++;
4530 }
4531 return test_main(argc, argv - argc);
4532}
4533
4534static int builtin_echo(char **argv)
4535{
4536 int argc = 0;
4537 while (*argv) {
4538 argc++;
4539 argv++;
4540 }
4541 return echo_main(argc, argv - argc);
4542}
4543
4544static int builtin_eval(char **argv)
4545{
4546 int rcode = EXIT_SUCCESS;
4547
4548 if (argv[1]) {
4549 char *str = expand_strvec_to_string(argv + 1);
4550 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4551 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004552 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004553 }
4554 return rcode;
4555}
4556
4557static int builtin_cd(char **argv)
4558{
4559 const char *newdir;
4560 if (argv[1] == NULL) {
4561 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4562 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4563 newdir = getenv("HOME") ? : "/";
4564 } else
4565 newdir = argv[1];
4566 if (chdir(newdir)) {
4567 printf("cd: %s: %s\n", newdir, strerror(errno));
4568 return EXIT_FAILURE;
4569 }
4570 set_cwd();
4571 return EXIT_SUCCESS;
4572}
4573
4574static int builtin_exec(char **argv)
4575{
4576 if (argv[1] == NULL)
4577 return EXIT_SUCCESS; /* bash does this */
4578 {
4579#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004580 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004581#endif
4582// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004583 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004584 /* never returns */
4585 }
4586}
4587
4588static int builtin_exit(char **argv)
4589{
4590// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4591 //puts("exit"); /* bash does it */
4592// TODO: warn if we have background jobs: "There are stopped jobs"
4593// On second consecutive 'exit', exit anyway.
4594 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004595 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004596 /* mimic bash: exit 123abc == exit 255 + error msg */
4597 xfunc_error_retval = 255;
4598 /* bash: exit -2 == exit 254, no error msg */
4599 hush_exit(xatoi(argv[1]) & 0xff);
4600}
4601
4602static int builtin_export(char **argv)
4603{
4604 const char *value;
4605 char *name = argv[1];
4606
4607 if (name == NULL) {
4608 // TODO:
4609 // ash emits: export VAR='VAL'
4610 // bash: declare -x VAR="VAL"
4611 // (both also escape as needed (quotes, $, etc))
4612 char **e = environ;
4613 if (e)
4614 while (*e)
4615 puts(*e++);
4616 return EXIT_SUCCESS;
4617 }
4618
4619 value = strchr(name, '=');
4620 if (!value) {
4621 /* They are exporting something without a =VALUE */
4622 struct variable *var;
4623
4624 var = get_local_var(name);
4625 if (var) {
4626 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004627 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004628 putenv(var->varstr);
4629 }
4630 /* bash does not return an error when trying to export
4631 * an undefined variable. Do likewise. */
4632 return EXIT_SUCCESS;
4633 }
4634
4635 set_local_var(xstrdup(name), 1);
4636 return EXIT_SUCCESS;
4637}
4638
4639#if ENABLE_HUSH_JOB
4640/* built-in 'fg' and 'bg' handler */
4641static int builtin_fg_bg(char **argv)
4642{
4643 int i, jobnum;
4644 struct pipe *pi;
4645
Denis Vlasenko87a86552008-07-29 19:43:10 +00004646 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004647 return EXIT_FAILURE;
4648 /* If they gave us no args, assume they want the last backgrounded task */
4649 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004650 for (pi = G.job_list; pi; pi = pi->next) {
4651 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004652 goto found;
4653 }
4654 }
4655 bb_error_msg("%s: no current job", argv[0]);
4656 return EXIT_FAILURE;
4657 }
4658 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4659 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4660 return EXIT_FAILURE;
4661 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004662 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004663 if (pi->jobid == jobnum) {
4664 goto found;
4665 }
4666 }
4667 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4668 return EXIT_FAILURE;
4669 found:
4670 // TODO: bash prints a string representation
4671 // of job being foregrounded (like "sleep 1 | cat")
4672 if (*argv[0] == 'f') {
4673 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004674 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004675 }
4676
4677 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004678 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4679 for (i = 0; i < pi->num_cmds; i++) {
4680 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4681 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004682 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004683 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004684
4685 i = kill(- pi->pgrp, SIGCONT);
4686 if (i < 0) {
4687 if (errno == ESRCH) {
4688 delete_finished_bg_job(pi);
4689 return EXIT_SUCCESS;
4690 } else {
4691 bb_perror_msg("kill (SIGCONT)");
4692 }
4693 }
4694
4695 if (*argv[0] == 'f') {
4696 remove_bg_job(pi);
4697 return checkjobs_and_fg_shell(pi);
4698 }
4699 return EXIT_SUCCESS;
4700}
4701#endif
4702
4703#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004704static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004705{
4706 const struct built_in_command *x;
4707
4708 printf("\nBuilt-in commands:\n");
4709 printf("-------------------\n");
4710 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4711 printf("%s\t%s\n", x->cmd, x->descr);
4712 }
4713 printf("\n\n");
4714 return EXIT_SUCCESS;
4715}
4716#endif
4717
4718#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004719static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004720{
4721 struct pipe *job;
4722 const char *status_string;
4723
Denis Vlasenko87a86552008-07-29 19:43:10 +00004724 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004725 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004726 status_string = "Stopped";
4727 else
4728 status_string = "Running";
4729
4730 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4731 }
4732 return EXIT_SUCCESS;
4733}
4734#endif
4735
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004736static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004737{
4738 puts(set_cwd());
4739 return EXIT_SUCCESS;
4740}
4741
4742static int builtin_read(char **argv)
4743{
4744 char *string;
4745 const char *name = argv[1] ? argv[1] : "REPLY";
4746
4747 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4748 return set_local_var(string, 0);
4749}
4750
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004751/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4752 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004753 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004754 * set [-abCefhmnuvx] [-o option] [argument...]
4755 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004756 * set -- [argument...]
4757 * set -o
4758 * set +o
4759 * Implementations shall support the options in both their hyphen and
4760 * plus-sign forms. These options can also be specified as options to sh.
4761 * Examples:
4762 * Write out all variables and their values: set
4763 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4764 * Turn on the -x and -v options: set -xv
4765 * Unset all positional parameters: set --
4766 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4767 * Set the positional parameters to the expansion of x, even if x expands
4768 * with a leading '-' or '+': set -- $x
4769 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004770 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004771 */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004772static int builtin_set_mode(const char cstate, const char mode)
4773{
4774 int state = (cstate == '-' ? 1 : 0);
4775 switch (mode) {
4776 case 'n': G.fake_mode = state; break;
4777 case 'x': /*G.debug_mode = state;*/ break;
4778 default: return EXIT_FAILURE;
4779 }
4780 return EXIT_SUCCESS;
4781}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004782static int builtin_set(char **argv)
4783{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004784 int n;
4785 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004786 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004787
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004788 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004789 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004790 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004791 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004792 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004793 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004794
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004795 do {
4796 if (!strcmp(arg, "--")) {
4797 ++argv;
4798 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004799 }
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004800
4801 if (arg[0] == '+' || arg[0] == '-') {
4802 for (n = 1; arg[n]; ++n)
4803 if (builtin_set_mode(arg[0], arg[n]))
4804 goto error;
4805 continue;
4806 }
4807
4808 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004809 } while ((arg = *++argv) != NULL);
4810 /* Now argv[0] is 1st argument */
4811
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004812 /* Only reset global_argv if we didn't process anything */
4813 if (arg == NULL)
4814 return EXIT_SUCCESS;
4815 set_argv:
4816
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004817 /* NB: G.global_argv[0] ($0) is never freed/changed */
4818 g_argv = G.global_argv;
4819 if (G.global_args_malloced) {
4820 pp = g_argv;
4821 while (*++pp)
4822 free(*pp);
4823 g_argv[1] = NULL;
4824 } else {
4825 G.global_args_malloced = 1;
4826 pp = xzalloc(sizeof(pp[0]) * 2);
4827 pp[0] = g_argv[0]; /* retain $0 */
4828 g_argv = pp;
4829 }
4830 /* This realloc's G.global_argv */
4831 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4832
4833 n = 1;
4834 while (*++pp)
4835 n++;
4836 G.global_argc = n;
4837
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004838 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004839
4840 /* Nothing known, so abort */
4841 error:
4842 bb_error_msg("set: %s: invalid option", arg);
4843 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004844}
4845
4846static int builtin_shift(char **argv)
4847{
4848 int n = 1;
4849 if (argv[1]) {
4850 n = atoi(argv[1]);
4851 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004852 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004853 if (G.global_args_malloced) {
4854 int m = 1;
4855 while (m <= n)
4856 free(G.global_argv[m++]);
4857 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004858 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004859 memmove(&G.global_argv[1], &G.global_argv[n+1],
4860 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004861 return EXIT_SUCCESS;
4862 }
4863 return EXIT_FAILURE;
4864}
4865
4866static int builtin_source(char **argv)
4867{
4868 FILE *input;
4869 int status;
4870
4871 if (argv[1] == NULL)
4872 return EXIT_FAILURE;
4873
4874 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004875 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004876 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004877 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004878 return EXIT_FAILURE;
4879 }
4880 close_on_exec_on(fileno(input));
4881
4882 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004883 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004884 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00004885 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004886 status = parse_and_run_file(input);
4887 fclose(input);
4888 return status;
4889}
4890
4891static int builtin_umask(char **argv)
4892{
4893 mode_t new_umask;
4894 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004895 if (arg) {
Mike Frysinger40b8dc42009-03-29 00:50:30 +00004896 new_umask = bb_strtou(arg, NULL, 8);
4897 if (errno)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004898 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004899 } else {
4900 new_umask = umask(0);
4901 printf("%.3o\n", (unsigned) new_umask);
4902 }
4903 umask(new_umask);
4904 return EXIT_SUCCESS;
4905}
4906
4907static int builtin_unset(char **argv)
4908{
4909 /* bash always returns true */
4910 unset_local_var(argv[1]);
4911 return EXIT_SUCCESS;
4912}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004913
Mike Frysinger56bdea12009-03-28 20:01:58 +00004914/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
4915static int builtin_wait(char **argv)
4916{
4917 int ret = EXIT_SUCCESS;
4918 int status;
4919
4920 if (argv[1] == NULL)
4921 /* don't care about exit status */
4922 wait(&status);
4923
4924 while (argv[1]) {
Mike Frysinger40b8dc42009-03-29 00:50:30 +00004925 pid_t pid = bb_strtou(argv[1], NULL, 10);
4926 if (errno) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00004927 bb_perror_msg("wait %s", argv[1]);
4928 return EXIT_FAILURE;
4929 } else if (waitpid(pid, &status, 0) == pid) {
4930 if (WIFSIGNALED(status))
4931 ret = 128 + WTERMSIG(status);
4932 else if (WIFEXITED(status))
4933 ret = WEXITSTATUS(status);
4934 else
4935 ret = EXIT_FAILURE;
4936 } else {
4937 bb_perror_msg("wait %s", argv[1]);
4938 ret = 127;
4939 }
4940 ++argv;
4941 }
4942
4943 return ret;
4944}
4945
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004946#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004947static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004948{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004949 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004950 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004951 return EXIT_SUCCESS; /* bash compat */
4952 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004953 G.flag_break_continue++; /* BC_BREAK = 1 */
4954 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004955 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004956 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4957 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004958 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004959 G.flag_break_continue = BC_BREAK;
4960 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004961 }
4962 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004963 if (G.depth_of_loop < G.depth_break_continue)
4964 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004965 return EXIT_SUCCESS;
4966}
4967
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004968static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004969{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004970 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4971 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004972}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004973#endif