blob: 3ab96a3236c3bb4dd93c89d929ed9ec9efae88cd [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);
527#if ENABLE_HUSH_LOOPS
528static int builtin_break(char **argv);
529static int builtin_continue(char **argv);
530#endif
531//static int builtin_not_written(char **argv);
532
533/* Table of built-in functions. They can be forked or not, depending on
534 * context: within pipes, they fork. As simple commands, they do not.
535 * When used in non-forking context, they can change global variables
536 * in the parent shell process. If forked, of course they cannot.
537 * For example, 'unset foo | whatever' will parse and run, but foo will
538 * still be set at the end. */
539struct built_in_command {
540 const char *cmd;
541 int (*function)(char **argv);
542#if ENABLE_HUSH_HELP
543 const char *descr;
544#define BLTIN(cmd, func, help) { cmd, func, help }
545#else
546#define BLTIN(cmd, func, help) { cmd, func }
547#endif
548};
549
550/* For now, echo and test are unconditionally enabled.
551 * Maybe make it configurable? */
552static const struct built_in_command bltins[] = {
553 BLTIN("." , builtin_source, "Run commands in a file"),
554 BLTIN(":" , builtin_true, "No-op"),
555 BLTIN("[" , builtin_test, "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000556#if ENABLE_HUSH_JOB
557 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
558#endif
559#if ENABLE_HUSH_LOOPS
560 BLTIN("break" , builtin_break, "Exit from a loop"),
561#endif
562 BLTIN("cd" , builtin_cd, "Change directory"),
563#if ENABLE_HUSH_LOOPS
564 BLTIN("continue", builtin_continue, "Start new loop iteration"),
565#endif
566 BLTIN("echo" , builtin_echo, "Write to stdout"),
567 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
568 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
569 BLTIN("exit" , builtin_exit, "Exit"),
570 BLTIN("export", builtin_export, "Set environment variable"),
571#if ENABLE_HUSH_JOB
572 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
573 BLTIN("jobs" , builtin_jobs, "List active jobs"),
574#endif
575 BLTIN("pwd" , builtin_pwd, "Print current directory"),
576 BLTIN("read" , builtin_read, "Input environment variable"),
577// BLTIN("return", builtin_not_written, "Return from a function"),
578 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
579 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
580// BLTIN("trap" , builtin_not_written, "Trap signals"),
581 BLTIN("test" , builtin_test, "Test condition"),
582// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
583 BLTIN("umask" , builtin_umask, "Set file creation mask"),
584 BLTIN("unset" , builtin_unset, "Unset environment variable"),
585#if ENABLE_HUSH_HELP
586 BLTIN("help" , builtin_help, "List shell built-in commands"),
587#endif
588};
589
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000590
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000591/* Normal */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000592static void maybe_die(const char *notice, const char *msg)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000593{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000594 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000595 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000596 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000597 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
598#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +0000599 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000600#endif
Mike Frysinger6379bb42009-03-28 18:55:03 +0000601 fp(msg ? "%s: %s" : notice, notice, msg);
602}
Mike Frysinger5a828452009-03-28 19:09:04 +0000603#if 1
604#define syntax(msg) maybe_die("syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000605#else
Mike Frysinger5a828452009-03-28 19:09:04 +0000606/* Debug -- trick gcc to expand __LINE__ and convert to string */
607#define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
608#define _syntax(msg, line) __syntax(msg, line)
609#define syntax(msg) _syntax(msg, __LINE__)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000610#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000611
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000612static int glob_needed(const char *s)
613{
614 while (*s) {
615 if (*s == '\\')
616 s++;
617 if (*s == '*' || *s == '[' || *s == '?')
618 return 1;
619 s++;
620 }
621 return 0;
622}
623
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000624static int is_assignment(const char *s)
625{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000626 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000627 return 0;
628 s++;
629 while (isalnum(*s) || *s == '_')
630 s++;
631 return *s == '=';
632}
633
Denis Vlasenko55789c62008-06-18 16:30:42 +0000634/* Replace each \x with x in place, return ptr past NUL. */
635static char *unbackslash(char *src)
636{
637 char *dst = src;
638 while (1) {
639 if (*src == '\\')
640 src++;
641 if ((*dst++ = *src++) == '\0')
642 break;
643 }
644 return dst;
645}
646
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000647static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000648{
649 int i;
650 unsigned count1;
651 unsigned count2;
652 char **v;
653
654 v = strings;
655 count1 = 0;
656 if (v) {
657 while (*v) {
658 count1++;
659 v++;
660 }
661 }
662 count2 = 0;
663 v = add;
664 while (*v) {
665 count2++;
666 v++;
667 }
668 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
669 v[count1 + count2] = NULL;
670 i = count2;
671 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000672 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000673 return v;
674}
675
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000676static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000677{
678 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000679 v[0] = add;
680 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000681 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000682}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000683
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000684static void putenv_all(char **strings)
685{
686 if (!strings)
687 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000688 while (*strings) {
689 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000690 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000691 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000692}
693
694static char **putenv_all_and_save_old(char **strings)
695{
696 char **old = NULL;
697 char **s = strings;
698
699 if (!strings)
700 return old;
701 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000702 char *v, *eq;
703
704 eq = strchr(*strings, '=');
705 if (eq) {
706 *eq = '\0';
707 v = getenv(*strings);
708 *eq = '=';
709 if (v) {
710 /* v points to VAL in VAR=VAL, go back to VAR */
711 v -= (eq - *strings) + 1;
712 old = add_string_to_strings(old, v);
713 }
714 }
715 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000716 }
717 putenv_all(s);
718 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000719}
720
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000721static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000722{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000723 char **v;
724
725 if (!strings)
726 return;
727
728 v = strings;
729 while (*v) {
730 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000731 debug_printf_env("unsetenv '%s'\n", *v);
732 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000733 }
734 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000735 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000736 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000737}
738
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000739static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000740{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000741 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000742}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000743
744
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000745/* Signals are grouped, we handle them in batches */
746static void set_misc_sighandler(void (*handler)(int))
747{
748 bb_signals(0
749 + (1 << SIGINT)
750 + (1 << SIGQUIT)
751 + (1 << SIGTERM)
752 , handler);
753}
754
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000755#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000756
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000757static void set_fatal_sighandler(void (*handler)(int))
758{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000759 bb_signals(0
760 + (1 << SIGILL)
761 + (1 << SIGTRAP)
762 + (1 << SIGABRT)
763 + (1 << SIGFPE)
764 + (1 << SIGBUS)
765 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000766 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000767 + (1 << SIGHUP)
768 + (1 << SIGPIPE)
769 + (1 << SIGALRM)
770 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000771}
772static void set_jobctrl_sighandler(void (*handler)(int))
773{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000774 bb_signals(0
775 + (1 << SIGTSTP)
776 + (1 << SIGTTIN)
777 + (1 << SIGTTOU)
778 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000779}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000780/* SIGCHLD is special and handled separately */
781
782static void set_every_sighandler(void (*handler)(int))
783{
784 set_fatal_sighandler(handler);
785 set_jobctrl_sighandler(handler);
786 set_misc_sighandler(handler);
787 signal(SIGCHLD, handler);
788}
789
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000790static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000791{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000792 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000793// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000794 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000795}
796
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000797static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000798{
799 pid_t pid;
800
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000801 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Mike Frysingerbfc0fae2009-03-26 18:14:16 +0000802
803 if (!BB_MMU) {
804 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
805 return;
806 }
807
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000808 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000809 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000810 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000811 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000812 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000813 if (ENABLE_HUSH_JOB)
814 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000815 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000816 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000817 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000818 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000819 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000820 /* return to nofork, it will eventually exit now,
821 * not return back to shell */
822 return;
823 }
824 /* parent */
825 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000826 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000827 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000828 /* parent needs to longjmp out of running nofork.
829 * we will "return" exitcode 0, with child put in background */
830// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000831 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000832 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000833}
834
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000835/* Restores tty foreground process group, and exits.
836 * May be called as signal handler for fatal signal
837 * (will faithfully resend signal to itself, producing correct exit state)
838 * or called directly with -EXITCODE.
839 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000840static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000841static void sigexit(int sig)
842{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000843 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000844 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000845
Denis Vlasenko87a86552008-07-29 19:43:10 +0000846#if ENABLE_HUSH_INTERACTIVE
847 if (G.interactive_fd)
848 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
849#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000850
851 /* Not a signal, just exit */
852 if (sig <= 0)
853 _exit(- sig);
854
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000855 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000856}
857
858/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000859static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000860static void hush_exit(int exitcode)
861{
862 fflush(NULL); /* flush all streams */
863 sigexit(- (exitcode & 0xff));
864}
865
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000866#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000867
868#define set_fatal_sighandler(handler) ((void)0)
869#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000870#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000871
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000872#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000873
874
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000875static const char *set_cwd(void)
876{
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000877 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
878 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000879 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000880 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000881 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
882 if (!G.cwd)
883 G.cwd = bb_msg_unknown;
884 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000885}
886
Denis Vlasenko83506862007-11-23 13:11:42 +0000887
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000888/* Get/check local shell variables */
889static struct variable *get_local_var(const char *name)
890{
891 struct variable *cur;
892 int len;
893
894 if (!name)
895 return NULL;
896 len = strlen(name);
897 for (cur = G.top_var; cur; cur = cur->next) {
898 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
899 return cur;
900 }
901 return NULL;
902}
903
904/* Basically useful version until someone wants to get fancier,
905 * see the bash man page under "Parameter Expansion" */
906static const char *lookup_param(const char *src)
907{
908 struct variable *var = get_local_var(src);
909 if (var)
910 return strchr(var->varstr, '=') + 1;
911 return NULL;
912}
913
914/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +0000915 * We take ownership of it.
916 * flg_export is used by:
917 * 0: do not export
918 * 1: export
919 * -1: if NAME is set, leave export status alone
920 * if NAME is not set, do not export
921 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000922static int set_local_var(char *str, int flg_export)
923{
924 struct variable *cur;
925 char *value;
926 int name_len;
927
928 value = strchr(str, '=');
929 if (!value) { /* not expected to ever happen? */
930 free(str);
931 return -1;
932 }
933
934 name_len = value - str + 1; /* including '=' */
935 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
936 while (1) {
937 if (strncmp(cur->varstr, str, name_len) != 0) {
938 if (!cur->next) {
939 /* Bail out. Note that now cur points
940 * to last var in linked list */
941 break;
942 }
943 cur = cur->next;
944 continue;
945 }
946 /* We found an existing var with this name */
947 *value = '\0';
948 if (cur->flg_read_only) {
949 bb_error_msg("%s: readonly variable", str);
950 free(str);
951 return -1;
952 }
953 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
954 unsetenv(str); /* just in case */
955 *value = '=';
956 if (strcmp(cur->varstr, str) == 0) {
957 free_and_exp:
958 free(str);
959 goto exp;
960 }
961 if (cur->max_len >= strlen(str)) {
962 /* This one is from startup env, reuse space */
963 strcpy(cur->varstr, str);
964 goto free_and_exp;
965 }
966 /* max_len == 0 signifies "malloced" var, which we can
967 * (and has to) free */
968 if (!cur->max_len)
969 free(cur->varstr);
970 cur->max_len = 0;
971 goto set_str_and_exp;
972 }
973
974 /* Not found - create next variable struct */
975 cur->next = xzalloc(sizeof(*cur));
976 cur = cur->next;
977
978 set_str_and_exp:
979 cur->varstr = str;
980 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +0000981 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000982 cur->flg_export = 1;
983 if (cur->flg_export) {
984 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
985 return putenv(cur->varstr);
986 }
987 return 0;
988}
989
990static void unset_local_var(const char *name)
991{
992 struct variable *cur;
993 struct variable *prev = prev; /* for gcc */
994 int name_len;
995
996 if (!name)
997 return;
998 name_len = strlen(name);
999 cur = G.top_var;
1000 while (cur) {
1001 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1002 if (cur->flg_read_only) {
1003 bb_error_msg("%s: readonly variable", name);
1004 return;
1005 }
1006 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1007 * is ro, and we cannot reach this code on the 1st pass */
1008 prev->next = cur->next;
1009 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1010 bb_unsetenv(cur->varstr);
1011 if (!cur->max_len)
1012 free(cur->varstr);
1013 free(cur);
1014 return;
1015 }
1016 prev = cur;
1017 cur = cur->next;
1018 }
1019}
1020
1021
1022/*
1023 * in_str support
1024 */
1025static int static_get(struct in_str *i)
1026{
1027 int ch = *i->p++;
1028 if (ch == '\0') return EOF;
1029 return ch;
1030}
1031
1032static int static_peek(struct in_str *i)
1033{
1034 return *i->p;
1035}
1036
1037#if ENABLE_HUSH_INTERACTIVE
1038
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001039static void cmdedit_set_initial_prompt(void)
1040{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001041 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1042 G.PS1 = getenv("PS1");
1043 if (G.PS1 == NULL)
1044 G.PS1 = "\\w \\$ ";
1045 } else
1046 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001047}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001048
1049static const char* setup_prompt_string(int promptmode)
1050{
1051 const char *prompt_str;
1052 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001053 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1054 /* Set up the prompt */
1055 if (promptmode == 0) { /* PS1 */
1056 free((char*)G.PS1);
1057 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1058 prompt_str = G.PS1;
1059 } else
1060 prompt_str = G.PS2;
1061 } else
1062 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001063 debug_printf("result '%s'\n", prompt_str);
1064 return prompt_str;
1065}
1066
1067static void get_user_input(struct in_str *i)
1068{
1069 int r;
1070 const char *prompt_str;
1071
1072 prompt_str = setup_prompt_string(i->promptmode);
1073#if ENABLE_FEATURE_EDITING
1074 /* Enable command line editing only while a command line
1075 * is actually being read */
1076 do {
1077 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1078 } while (r == 0); /* repeat if Ctrl-C */
1079 i->eof_flag = (r < 0);
1080 if (i->eof_flag) { /* EOF/error detected */
1081 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1082 G.user_input_buf[1] = '\0';
1083 }
1084#else
1085 fputs(prompt_str, stdout);
1086 fflush(stdout);
1087 G.user_input_buf[0] = r = fgetc(i->file);
1088 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1089 i->eof_flag = (r == EOF);
1090#endif
1091 i->p = G.user_input_buf;
1092}
1093
1094#endif /* INTERACTIVE */
1095
1096/* This is the magic location that prints prompts
1097 * and gets data back from the user */
1098static int file_get(struct in_str *i)
1099{
1100 int ch;
1101
1102 /* If there is data waiting, eat it up */
1103 if (i->p && *i->p) {
1104#if ENABLE_HUSH_INTERACTIVE
1105 take_cached:
1106#endif
1107 ch = *i->p++;
1108 if (i->eof_flag && !*i->p)
1109 ch = EOF;
1110 } else {
1111 /* need to double check i->file because we might be doing something
1112 * more complicated by now, like sourcing or substituting. */
1113#if ENABLE_HUSH_INTERACTIVE
1114 if (G.interactive_fd && i->promptme && i->file == stdin) {
1115 do {
1116 get_user_input(i);
1117 } while (!*i->p); /* need non-empty line */
1118 i->promptmode = 1; /* PS2 */
1119 i->promptme = 0;
1120 goto take_cached;
1121 }
1122#endif
1123 ch = fgetc(i->file);
1124 }
1125 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1126#if ENABLE_HUSH_INTERACTIVE
1127 if (ch == '\n')
1128 i->promptme = 1;
1129#endif
1130 return ch;
1131}
1132
1133/* All the callers guarantee this routine will never be
1134 * used right after a newline, so prompting is not needed.
1135 */
1136static int file_peek(struct in_str *i)
1137{
1138 int ch;
1139 if (i->p && *i->p) {
1140 if (i->eof_flag && !i->p[1])
1141 return EOF;
1142 return *i->p;
1143 }
1144 ch = fgetc(i->file);
1145 i->eof_flag = (ch == EOF);
1146 i->peek_buf[0] = ch;
1147 i->peek_buf[1] = '\0';
1148 i->p = i->peek_buf;
1149 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1150 return ch;
1151}
1152
1153static void setup_file_in_str(struct in_str *i, FILE *f)
1154{
1155 i->peek = file_peek;
1156 i->get = file_get;
1157#if ENABLE_HUSH_INTERACTIVE
1158 i->promptme = 1;
1159 i->promptmode = 0; /* PS1 */
1160#endif
1161 i->file = f;
1162 i->p = NULL;
1163}
1164
1165static void setup_string_in_str(struct in_str *i, const char *s)
1166{
1167 i->peek = static_peek;
1168 i->get = static_get;
1169#if ENABLE_HUSH_INTERACTIVE
1170 i->promptme = 1;
1171 i->promptmode = 0; /* PS1 */
1172#endif
1173 i->p = s;
1174 i->eof_flag = 0;
1175}
1176
1177
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001178/*
1179 * o_string support
1180 */
1181#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001182
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001183static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001184{
1185 o->length = 0;
1186 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001187 if (o->data)
1188 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001189}
1190
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001191static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001192{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001193 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001194 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001195}
1196
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001197static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001198{
1199 if (o->length + len > o->maxlen) {
1200 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1201 o->data = xrealloc(o->data, 1 + o->maxlen);
1202 }
1203}
1204
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001205static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001206{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001207 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1208 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001209 o->data[o->length] = ch;
1210 o->length++;
1211 o->data[o->length] = '\0';
1212}
1213
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001214static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001215{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001216 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001217 memcpy(&o->data[o->length], str, len);
1218 o->length += len;
1219 o->data[o->length] = '\0';
1220}
1221
Denis Vlasenko55789c62008-06-18 16:30:42 +00001222static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1223{
1224 while (len) {
1225 o_addchr(o, *str);
1226 if (*str++ == '\\'
1227 && (*str != '*' && *str != '?' && *str != '[')
1228 ) {
1229 o_addchr(o, '\\');
1230 }
1231 len--;
1232 }
1233}
1234
Eric Andersen25f27032001-04-26 23:22:31 +00001235/* My analysis of quoting semantics tells me that state information
1236 * is associated with a destination, not a source.
1237 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001238static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001239{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001240 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001241 char *found = strchr("*?[\\", ch);
1242 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001243 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001244 o_grow_by(o, sz);
1245 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001246 o->data[o->length] = '\\';
1247 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001248 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001249 o->data[o->length] = ch;
1250 o->length++;
1251 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001252}
1253
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001254static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001255{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001256 int sz = 1;
1257 if (o->o_quote && strchr("*?[\\", ch)) {
1258 sz++;
1259 o->data[o->length] = '\\';
1260 o->length++;
1261 }
1262 o_grow_by(o, sz);
1263 o->data[o->length] = ch;
1264 o->length++;
1265 o->data[o->length] = '\0';
1266}
1267
1268static void o_addQstr(o_string *o, const char *str, int len)
1269{
1270 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001271 o_addstr(o, str, len);
1272 return;
1273 }
1274 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001275 char ch;
1276 int sz;
1277 int ordinary_cnt = strcspn(str, "*?[\\");
1278 if (ordinary_cnt > len) /* paranoia */
1279 ordinary_cnt = len;
1280 o_addstr(o, str, ordinary_cnt);
1281 if (ordinary_cnt == len)
1282 return;
1283 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001284 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001285
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001286 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001287 sz = 1;
1288 if (ch) { /* it is necessarily one of "*?[\\" */
1289 sz++;
1290 o->data[o->length] = '\\';
1291 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001292 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001293 o_grow_by(o, sz);
1294 o->data[o->length] = ch;
1295 o->length++;
1296 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001297 }
1298}
1299
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001300/* A special kind of o_string for $VAR and `cmd` expansion.
1301 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001302 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001303 * list[i] contains an INDEX (int!) into this string data.
1304 * It means that if list[] needs to grow, data needs to be moved higher up
1305 * but list[i]'s need not be modified.
1306 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001307 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001308 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1309 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001310#if DEBUG_EXPAND || DEBUG_GLOB
1311static void debug_print_list(const char *prefix, o_string *o, int n)
1312{
1313 char **list = (char**)o->data;
1314 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1315 int i = 0;
1316 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1317 prefix, list, n, string_start, o->length, o->maxlen);
1318 while (i < n) {
1319 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1320 o->data + (int)list[i] + string_start,
1321 o->data + (int)list[i] + string_start);
1322 i++;
1323 }
1324 if (n) {
1325 const char *p = o->data + (int)list[n - 1] + string_start;
Mike Frysingerd006edb2009-03-28 12:43:53 +00001326 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001327 }
1328}
1329#else
1330#define debug_print_list(prefix, o, n) ((void)0)
1331#endif
1332
1333/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1334 * in list[n] so that it points past last stored byte so far.
1335 * It returns n+1. */
1336static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001337{
1338 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001339 int string_start;
1340 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001341
1342 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001343 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1344 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001345 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001346 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001347 /* list[n] points to string_start, make space for 16 more pointers */
1348 o->maxlen += 0x10 * sizeof(list[0]);
1349 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001350 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001351 memmove(list + n + 0x10, list + n, string_len);
1352 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001353 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001354 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001355 } else {
1356 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001357 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1358 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001359 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001360 o->has_empty_slot = 0;
1361 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001362 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001363 return n + 1;
1364}
1365
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001366/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001367static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001368{
1369 char **list = (char**)o->data;
1370 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1371
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001372 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001373}
1374
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001375/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001376 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001377static int o_glob(o_string *o, int n)
1378{
1379 glob_t globdata;
1380 int gr;
1381 char *pattern;
1382
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001383 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001384 if (!o->data)
1385 return o_save_ptr_helper(o, n);
1386 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001387 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001388 if (!glob_needed(pattern)) {
1389 literal:
1390 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001391 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001392 return o_save_ptr_helper(o, n);
1393 }
1394
1395 memset(&globdata, 0, sizeof(globdata));
1396 gr = glob(pattern, 0, NULL, &globdata);
1397 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1398 if (gr == GLOB_NOSPACE)
1399 bb_error_msg_and_die("out of memory during glob");
1400 if (gr == GLOB_NOMATCH) {
1401 globfree(&globdata);
1402 goto literal;
1403 }
1404 if (gr != 0) { /* GLOB_ABORTED ? */
1405//TODO: testcase for bad glob pattern behavior
1406 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1407 }
1408 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1409 char **argv = globdata.gl_pathv;
1410 o->length = pattern - o->data; /* "forget" pattern */
1411 while (1) {
1412 o_addstr(o, *argv, strlen(*argv) + 1);
1413 n = o_save_ptr_helper(o, n);
1414 argv++;
1415 if (!*argv)
1416 break;
1417 }
1418 }
1419 globfree(&globdata);
1420 if (DEBUG_GLOB)
1421 debug_print_list("o_glob returning", o, n);
1422 return n;
1423}
1424
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001425/* If o->o_glob == 1, glob the string so far remembered.
1426 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001427static int o_save_ptr(o_string *o, int n)
1428{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001429 if (o->o_glob) { /* if globbing is requested */
1430 /* If o->has_empty_slot, list[n] was already globbed
1431 * (if it was requested back then when it was filled)
1432 * so don't do that again! */
1433 if (!o->has_empty_slot)
1434 return o_glob(o, n); /* o_save_ptr_helper is inside */
1435 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001436 return o_save_ptr_helper(o, n);
1437}
1438
1439/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001440static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001441{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001442 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001443 int string_start;
1444
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001445 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1446 if (DEBUG_EXPAND)
1447 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001448 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001449 list = (char**)o->data;
1450 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1451 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001452 while (n) {
1453 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001454 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001455 }
1456 return list;
1457}
1458
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001459
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001460/* expand_strvec_to_strvec() takes a list of strings, expands
1461 * all variable references within and returns a pointer to
1462 * a list of expanded strings, possibly with larger number
1463 * of strings. (Think VAR="a b"; echo $VAR).
1464 * This new list is allocated as a single malloc block.
1465 * NULL-terminated list of char* pointers is at the beginning of it,
1466 * followed by strings themself.
1467 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001468
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001469/* Store given string, finalizing the word and starting new one whenever
1470 * we encounter IFS char(s). This is used for expanding variable values.
1471 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1472static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001473{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001474 while (1) {
1475 int word_len = strcspn(str, G.ifs);
1476 if (word_len) {
1477 if (output->o_quote || !output->o_glob)
1478 o_addQstr(output, str, word_len);
1479 else /* protect backslashes against globbing up :) */
1480 o_addstr_duplicate_backslash(output, str, word_len);
1481 str += word_len;
1482 }
1483 if (!*str) /* EOL - do not finalize word */
1484 break;
1485 o_addchr(output, '\0');
1486 debug_print_list("expand_on_ifs", output, n);
1487 n = o_save_ptr(output, n);
1488 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001489 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001490 debug_print_list("expand_on_ifs[1]", output, n);
1491 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001492}
1493
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001494#if ENABLE_HUSH_TICK
1495static int process_command_subs(o_string *dest,
1496 struct in_str *input, const char *subst_end);
Eric Andersen25f27032001-04-26 23:22:31 +00001497#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001498
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001499/* Expand all variable references in given string, adding words to list[]
1500 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1501 * to be filled). This routine is extremely tricky: has to deal with
1502 * variables/parameters with whitespace, $* and $@, and constructs like
1503 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1504static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001505{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001506 /* or_mask is either 0 (normal case) or 0x80
1507 * (expansion of right-hand side of assignment == 1-element expand.
1508 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001509
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001510 char first_ch, ored_ch;
1511 int i;
1512 const char *val;
1513 char *p;
1514
1515 ored_ch = 0;
1516
1517 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1518 debug_print_list("expand_vars_to_list", output, n);
1519 n = o_save_ptr(output, n);
1520 debug_print_list("expand_vars_to_list[0]", output, n);
1521
1522 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1523#if ENABLE_HUSH_TICK
1524 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001525#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001526 o_addstr(output, arg, p - arg);
1527 debug_print_list("expand_vars_to_list[1]", output, n);
1528 arg = ++p;
1529 p = strchr(p, SPECIAL_VAR_SYMBOL);
1530
1531 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1532 /* "$@" is special. Even if quoted, it can still
1533 * expand to nothing (not even an empty string) */
1534 if ((first_ch & 0x7f) != '@')
1535 ored_ch |= first_ch;
1536 val = NULL;
1537 switch (first_ch & 0x7f) {
1538 /* Highest bit in first_ch indicates that var is double-quoted */
1539 case '$': /* pid */
1540 val = utoa(G.root_pid);
1541 break;
1542 case '!': /* bg pid */
1543 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1544 break;
1545 case '?': /* exitcode */
1546 val = utoa(G.last_return_code);
1547 break;
1548 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001549 if (arg[1] != SPECIAL_VAR_SYMBOL)
1550 /* actually, it's a ${#var} */
1551 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001552 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1553 break;
1554 case '*':
1555 case '@':
1556 i = 1;
1557 if (!G.global_argv[i])
1558 break;
1559 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1560 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1561 smallint sv = output->o_quote;
1562 /* unquoted var's contents should be globbed, so don't quote */
1563 output->o_quote = 0;
1564 while (G.global_argv[i]) {
1565 n = expand_on_ifs(output, n, G.global_argv[i]);
1566 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1567 if (G.global_argv[i++][0] && G.global_argv[i]) {
1568 /* this argv[] is not empty and not last:
1569 * put terminating NUL, start new word */
1570 o_addchr(output, '\0');
1571 debug_print_list("expand_vars_to_list[2]", output, n);
1572 n = o_save_ptr(output, n);
1573 debug_print_list("expand_vars_to_list[3]", output, n);
1574 }
1575 }
1576 output->o_quote = sv;
1577 } else
1578 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1579 * and in this case should treat it like '$*' - see 'else...' below */
1580 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1581 while (1) {
1582 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1583 if (++i >= G.global_argc)
1584 break;
1585 o_addchr(output, '\0');
1586 debug_print_list("expand_vars_to_list[4]", output, n);
1587 n = o_save_ptr(output, n);
1588 }
1589 } else { /* quoted $*: add as one word */
1590 while (1) {
1591 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1592 if (!G.global_argv[++i])
1593 break;
1594 if (G.ifs[0])
1595 o_addchr(output, G.ifs[0]);
1596 }
1597 }
1598 break;
1599 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1600 /* "Empty variable", used to make "" etc to not disappear */
1601 arg++;
1602 ored_ch = 0x80;
1603 break;
1604#if ENABLE_HUSH_TICK
1605 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1606 struct in_str input;
1607 *p = '\0';
1608 arg++;
1609//TODO: can we just stuff it into "output" directly?
1610 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1611 setup_string_in_str(&input, arg);
1612 process_command_subs(&subst_result, &input, NULL);
1613 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1614 val = subst_result.data;
1615 goto store_val;
Eric Andersen25f27032001-04-26 23:22:31 +00001616 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001617#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001618 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001619 case_default: {
1620 bool exp_len = false, exp_null = false;
1621 char *var = arg, exp_save, exp_op, *exp_word;
1622 size_t exp_off = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001623 *p = '\0';
1624 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001625
1626 /* prepare for expansions */
1627 if (var[0] == '#') {
1628 /* handle length expansion ${#var} */
1629 exp_len = true;
1630 ++var;
1631 } else {
1632 /* maybe handle parameter expansion */
1633 exp_off = strcspn(var, ":-=+?");
1634 if (!var[exp_off])
1635 exp_off = 0;
1636 if (exp_off) {
1637 exp_save = var[exp_off];
1638 exp_null = exp_save == ':';
1639 exp_word = var + exp_off;
1640 if (exp_null) ++exp_word;
1641 exp_op = *exp_word++;
1642 var[exp_off] = '\0';
1643 }
1644 }
1645
1646 /* lookup the variable in question */
1647 if (isdigit(var[0])) {
1648 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001649 if (i < G.global_argc)
1650 val = G.global_argv[i];
1651 /* else val remains NULL: $N with too big N */
1652 } else
Mike Frysinger6379bb42009-03-28 18:55:03 +00001653 val = lookup_param(var);
1654
1655 /* handle any expansions */
1656 if (exp_len) {
1657 debug_printf_expand("expand: length of '%s' = ", val);
1658 val = utoa(val ? strlen(val) : 0);
1659 debug_printf_expand("%s\n", val);
1660 } else if (exp_off) {
1661 /* we need to do an expansion */
1662 int exp_test = (!val || (exp_null && !val[0]));
1663 if (exp_op == '+')
1664 exp_test = !exp_test;
1665 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1666 exp_null ? "true" : "false", exp_test);
1667 if (exp_test) {
1668 if (exp_op == '?')
1669 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1670 else
1671 val = exp_word;
1672
1673 if (exp_op == '=') {
1674 if (isdigit(var[0]) || var[0] == '#') {
1675 maybe_die(var, "special vars cannot assign in this way");
1676 val = NULL;
1677 } else {
1678 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1679 sprintf(new_var, "%s=%s", var, val);
1680 set_local_var(new_var, -1);
1681 }
1682 }
1683 }
1684 var[exp_off] = exp_save;
1685 }
1686
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001687 arg[0] = first_ch;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001688
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001689#if ENABLE_HUSH_TICK
1690 store_val:
1691#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001692 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1693 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1694 if (val) {
1695 /* unquoted var's contents should be globbed, so don't quote */
1696 smallint sv = output->o_quote;
1697 output->o_quote = 0;
1698 n = expand_on_ifs(output, n, val);
1699 val = NULL;
1700 output->o_quote = sv;
1701 }
1702 } else { /* quoted $VAR, val will be appended below */
1703 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1704 }
1705 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001706 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001707 if (val) {
1708 o_addQstr(output, val, strlen(val));
1709 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001710 /* Do the check to avoid writing to a const string */
1711 if (p && *p != SPECIAL_VAR_SYMBOL)
1712 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001713
1714#if ENABLE_HUSH_TICK
1715 o_free(&subst_result);
1716#endif
1717 arg = ++p;
1718 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1719
1720 if (arg[0]) {
1721 debug_print_list("expand_vars_to_list[a]", output, n);
1722 /* this part is literal, and it was already pre-quoted
1723 * if needed (much earlier), do not use o_addQstr here! */
1724 o_addstr(output, arg, strlen(arg) + 1);
1725 debug_print_list("expand_vars_to_list[b]", output, n);
1726 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1727 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1728 ) {
1729 n--;
1730 /* allow to reuse list[n] later without re-growth */
1731 output->has_empty_slot = 1;
1732 } else {
1733 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00001734 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001735 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001736}
1737
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001738static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001739{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001740 int n;
1741 char **list;
1742 char **v;
1743 o_string output = NULL_O_STRING;
1744
1745 if (or_mask & 0x100) {
1746 output.o_quote = 1; /* protect against globbing for "$var" */
1747 /* (unquoted $var will temporarily switch it off) */
1748 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001749 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001750
1751 n = 0;
1752 v = argv;
1753 while (*v) {
1754 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1755 v++;
1756 }
1757 debug_print_list("expand_variables", &output, n);
1758
1759 /* output.data (malloced in one block) gets returned in "list" */
1760 list = o_finalize_list(&output, n);
1761 debug_print_strings("expand_variables[1]", list);
1762 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00001763}
1764
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001765static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001766{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001767 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00001768}
1769
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001770/* Used for expansion of right hand of assignments */
1771/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1772 * "v=/bin/c*" */
1773static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001774{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001775 char *argv[2], **list;
1776
1777 argv[0] = (char*)str;
1778 argv[1] = NULL;
1779 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1780 if (HUSH_DEBUG)
1781 if (!list[0] || list[1])
1782 bb_error_msg_and_die("BUG in varexp2");
1783 /* actually, just move string 2*sizeof(char*) bytes back */
1784 overlapping_strcpy((char*)list, list[0]);
1785 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1786 return (char*)list;
1787}
1788
1789/* Used for "eval" builtin */
1790static char* expand_strvec_to_string(char **argv)
1791{
1792 char **list;
1793
1794 list = expand_variables(argv, 0x80);
1795 /* Convert all NULs to spaces */
1796 if (list[0]) {
1797 int n = 1;
1798 while (list[n]) {
1799 if (HUSH_DEBUG)
1800 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1801 bb_error_msg_and_die("BUG in varexp3");
1802 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1803 n++;
1804 }
1805 }
1806 overlapping_strcpy((char*)list, list[0]);
1807 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1808 return (char*)list;
1809}
1810
1811static char **expand_assignments(char **argv, int count)
1812{
1813 int i;
1814 char **p = NULL;
1815 /* Expand assignments into one string each */
1816 for (i = 0; i < count; i++) {
1817 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1818 }
1819 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00001820}
1821
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001822
Eric Andersen25f27032001-04-26 23:22:31 +00001823/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1824 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001825static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001826{
1827 int openfd, mode;
1828 struct redir_struct *redir;
1829
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001830 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001831 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001832 /* something went wrong in the parse. Pretend it didn't happen */
1833 continue;
1834 }
Eric Andersen25f27032001-04-26 23:22:31 +00001835 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001836 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001837 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001838//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001839 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001840 openfd = open_or_warn(p, mode);
1841 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001842 if (openfd < 0) {
1843 /* this could get lost if stderr has been redirected, but
1844 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001845 return 1;
1846 }
1847 } else {
1848 openfd = redir->dup;
1849 }
1850
1851 if (openfd != redir->fd) {
1852 if (squirrel && redir->fd < 3) {
1853 squirrel[redir->fd] = dup(redir->fd);
1854 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001855 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001856 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001857 } else {
1858 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001859 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001860 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001861 }
Eric Andersen25f27032001-04-26 23:22:31 +00001862 }
1863 }
1864 return 0;
1865}
1866
1867static void restore_redirects(int squirrel[])
1868{
1869 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001870 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001871 fd = squirrel[i];
1872 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001873 /* We simply die on error */
1874 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001875 }
1876 }
1877}
1878
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879
1880#if !defined(DEBUG_CLEAN)
1881#define free_pipe_list(head, indent) free_pipe_list(head)
1882#define free_pipe(pi, indent) free_pipe(pi)
1883#endif
1884static int free_pipe_list(struct pipe *head, int indent);
1885
1886/* return code is the exit status of the pipe */
1887static int free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001888{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001889 char **p;
1890 struct command *command;
1891 struct redir_struct *r, *rnext;
1892 int a, i, ret_code = 0;
1893
1894 if (pi->stopped_cmds > 0)
1895 return ret_code;
1896 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1897 for (i = 0; i < pi->num_cmds; i++) {
1898 command = &pi->cmds[i];
1899 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1900 if (command->argv) {
1901 for (a = 0, p = command->argv; *p; a++, p++) {
1902 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1903 }
1904 free_strings(command->argv);
1905 command->argv = NULL;
1906 } else if (command->group) {
1907 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1908 ret_code = free_pipe_list(command->group, indent+3);
1909 debug_printf_clean("%s end group\n", indenter(indent));
1910 } else {
1911 debug_printf_clean("%s (nil)\n", indenter(indent));
1912 }
1913 for (r = command->redirects; r; r = rnext) {
1914 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1915 if (r->dup == -1) {
1916 /* guard against the case >$FOO, where foo is unset or blank */
1917 if (r->rd_filename) {
1918 debug_printf_clean(" %s\n", r->rd_filename);
1919 free(r->rd_filename);
1920 r->rd_filename = NULL;
1921 }
1922 } else {
1923 debug_printf_clean("&%d\n", r->dup);
1924 }
1925 rnext = r->next;
1926 free(r);
1927 }
1928 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001929 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001930 free(pi->cmds); /* children are an array, they get freed all at once */
1931 pi->cmds = NULL;
1932#if ENABLE_HUSH_JOB
1933 free(pi->cmdtext);
1934 pi->cmdtext = NULL;
1935#endif
1936 return ret_code;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001937}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001938
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001939static int free_pipe_list(struct pipe *head, int indent)
1940{
1941 int rcode = 0; /* if list has no members */
1942 struct pipe *pi, *next;
1943
1944 for (pi = head; pi; pi = next) {
1945#if HAS_KEYWORDS
1946 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1947#endif
1948 rcode = free_pipe(pi, indent);
1949 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1950 next = pi->next;
1951 /*pi->next = NULL;*/
1952 free(pi);
1953 }
1954 return rcode;
1955}
1956
1957
1958#if !BB_MMU
1959typedef struct nommu_save_t {
1960 char **new_env;
1961 char **old_env;
1962 char **argv;
1963} nommu_save_t;
1964#else
1965#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1966 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1967#define pseudo_exec(nommu_save, command, argv_expanded) \
1968 pseudo_exec(command, argv_expanded)
1969#endif
1970
Denis Vlasenko05743d72008-02-10 12:10:08 +00001971/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001972 * Never returns.
1973 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001974 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001975 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001976static 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 +00001977static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001978{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001979 int rcode;
1980 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001981 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001982
Denis Vlasenko1359da62007-04-21 23:27:30 +00001983 /* If a variable is assigned in a forest, and nobody listens,
1984 * was it ever really set?
1985 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001986 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001987 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001988
Denis Vlasenko9504e442008-10-29 01:19:15 +00001989 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001990#if BB_MMU
1991 putenv_all(new_env);
1992 free(new_env); /* optional */
1993#else
1994 nommu_save->new_env = new_env;
1995 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001996#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001997 if (argv_expanded) {
1998 argv = argv_expanded;
1999 } else {
2000 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002001#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002002 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002003#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002004 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002005
Denis Vlasenko1359da62007-04-21 23:27:30 +00002006 /*
2007 * Check if the command matches any of the builtins.
2008 * Depending on context, this might be redundant. But it's
2009 * easier to waste a few CPU cycles than it is to figure out
2010 * if this is one of those cases.
2011 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002012 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00002013 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002014 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002015 rcode = x->function(argv);
2016 fflush(stdout);
2017 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00002018 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002019 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002020
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002021 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002022#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002023 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002024 int a = find_applet_by_name(argv[0]);
2025 if (a >= 0) {
2026 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002027 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002028// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2029 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002030 }
2031 /* re-exec ourselves with the new arguments */
2032 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00002033 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002034 /* If they called chroot or otherwise made the binary no longer
2035 * executable, fall through */
2036 }
2037 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002038#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002039
2040 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002041 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002042 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002043 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002044}
2045
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002046static int run_list(struct pipe *pi);
2047
Denis Vlasenko05743d72008-02-10 12:10:08 +00002048/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00002049 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002050static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002051static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002052{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002053 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002054 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002055
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002056 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00002057#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002058 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00002059#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00002060 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002061 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002062 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002063 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002064 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002065 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002066#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002067 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002068
2069 /* Can happen. See what bash does with ">foo" by itself. */
2070 debug_printf("trying to pseudo_exec null command\n");
2071 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002072}
2073
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002074#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002075static const char *get_cmdtext(struct pipe *pi)
2076{
2077 char **argv;
2078 char *p;
2079 int len;
2080
2081 /* This is subtle. ->cmdtext is created only on first backgrounding.
2082 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002083 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002084 if (pi->cmdtext)
2085 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002086 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002087 if (!argv || !argv[0]) {
2088 pi->cmdtext = xzalloc(1);
2089 return pi->cmdtext;
2090 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002091
2092 len = 0;
2093 do len += strlen(*argv) + 1; while (*++argv);
2094 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002095 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002096 do {
2097 len = strlen(*argv);
2098 memcpy(p, *argv, len);
2099 p += len;
2100 *p++ = ' ';
2101 } while (*++argv);
2102 p[-1] = '\0';
2103 return pi->cmdtext;
2104}
2105
Eric Andersenbafd94f2001-05-02 16:11:59 +00002106static void insert_bg_job(struct pipe *pi)
2107{
2108 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002109 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002110
2111 /* Linear search for the ID of the job to use */
2112 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002113 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002114 if (thejob->jobid >= pi->jobid)
2115 pi->jobid = thejob->jobid + 1;
2116
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002117 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002118 if (!G.job_list) {
2119 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002120 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002121 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002122 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002123 thejob->next = xmalloc(sizeof(*thejob));
2124 thejob = thejob->next;
2125 }
2126
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002127 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002128 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002129 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2130 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2131 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002132// TODO: do we really need to have so many fields which are just dead weight
2133// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002134 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002135 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002136 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002137 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002138 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002139
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002140 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002141 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002142 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2143 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002144 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002145}
2146
Eric Andersenbafd94f2001-05-02 16:11:59 +00002147static void remove_bg_job(struct pipe *pi)
2148{
2149 struct pipe *prev_pipe;
2150
Denis Vlasenko87a86552008-07-29 19:43:10 +00002151 if (pi == G.job_list) {
2152 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002153 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002154 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002155 while (prev_pipe->next != pi)
2156 prev_pipe = prev_pipe->next;
2157 prev_pipe->next = pi->next;
2158 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002159 if (G.job_list)
2160 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002161 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002162 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002163}
Eric Andersen028b65b2001-06-28 01:10:11 +00002164
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002165/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002166static void delete_finished_bg_job(struct pipe *pi)
2167{
2168 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002169 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002170 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002171 free(pi);
2172}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002173#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002174
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002175/* Check to see if any processes have exited -- if they
2176 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002177static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002178{
Eric Andersenc798b072001-06-22 06:23:03 +00002179 int attributes;
2180 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002181#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002182 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002183#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002184 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002185 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002186
Eric Andersenc798b072001-06-22 06:23:03 +00002187 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002188 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002189 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002190
Denis Vlasenko1359da62007-04-21 23:27:30 +00002191/* Do we do this right?
2192 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002193 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002194 * [3]+ Stopped sleep 20 | false
2195 * bash-3.00# echo $?
2196 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2197 */
2198
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002199//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2200//are stopped. Testcase: "cat | cat" in a script (not on command line)
2201// + killall -STOP cat
2202
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002203 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00002204// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00002205 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002206 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002207 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002208#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002209 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002210 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002211 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2212 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002213 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002214 childpid, WTERMSIG(status), WEXITSTATUS(status));
2215 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002216 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002217 childpid, WEXITSTATUS(status));
2218#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002219 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002220 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002221 for (i = 0; i < fg_pipe->num_cmds; i++) {
2222 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2223 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002224 continue;
2225 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2226 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002227 fg_pipe->cmds[i].pid = 0;
2228 fg_pipe->alive_cmds--;
2229 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002230 /* last process gives overall exitstatus */
2231 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002232 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002233 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002234 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002235 fg_pipe->cmds[i].is_stopped = 1;
2236 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002237 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002238 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2239 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2240 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002241 /* All processes in fg pipe have exited/stopped */
2242#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002243 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002244 insert_bg_job(fg_pipe);
2245#endif
2246 return rcode;
2247 }
2248 /* There are still running processes in the fg pipe */
2249 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002250 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002251 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002252 }
2253
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002254#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002255 /* We asked to wait for bg or orphaned children */
2256 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002257 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002258 for (i = 0; i < pi->num_cmds; i++) {
2259 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002260 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002261 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002262 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002263 /* Happens when shell is used as init process (init=/bin/sh) */
2264 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002265 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002266
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002267 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002268 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002269 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002270 pi->cmds[i].pid = 0;
2271 pi->alive_cmds--;
2272 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002273 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002274 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002275 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002276 }
2277 } else {
2278 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002279 pi->cmds[i].is_stopped = 1;
2280 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002281 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002282#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002283 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002284
Denis Vlasenko1359da62007-04-21 23:27:30 +00002285 /* wait found no children or failed */
2286
2287 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002288 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002289 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002290}
2291
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002292#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002293static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2294{
2295 pid_t p;
2296 int rcode = checkjobs(fg_pipe);
2297 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002298 p = getpgid(0); /* pgid of our process */
2299 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002300 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002301 return rcode;
2302}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002303#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002304
Denis Vlasenko05743d72008-02-10 12:10:08 +00002305/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00002306 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002307 *
2308 * return code is normally -1, when the caller has to wait for children
2309 * to finish to determine the exit status of the pipe. If the pipe
2310 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002311 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002312 * return value.
2313 *
2314 * The input of the pipe is always stdin, the output is always
2315 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2316 * because it tries to avoid running the command substitution in
2317 * subshell, when that is in fact necessary. The subshell process
2318 * now has its stdout directed to the input of the appropriate pipe,
2319 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00002320 *
2321 * Returns -1 only if started some children. IOW: we have to
2322 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00002323 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002324static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002325{
2326 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002327 int nextin;
2328 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002329 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002330 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002331 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00002332 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002333 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002334 /* it is not always needed, but we aim to smaller code */
2335 int squirrel[] = { -1, -1, -1 };
2336 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002337 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00002338
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002339 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002340
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002341#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00002342 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002343#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002344 pi->alive_cmds = 1;
2345 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002346
2347 /* Check if this is a simple builtin (not part of a pipe).
2348 * Builtins within pipes have to fork anyway, and are handled in
2349 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2350 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002351 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002352
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002353#if ENABLE_HUSH_FUNCTIONS
2354 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2355 /* We "execute" function definition */
2356 bb_error_msg("here we ought to remember function definition, and go on");
2357 return EXIT_SUCCESS;
2358 }
2359#endif
2360
2361 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00002362 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002363 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002364 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002365 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00002366 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002367 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002368 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00002369 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002370 }
2371
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002372 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002373 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002374
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002375 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002376 char **new_env = NULL;
2377 char **old_env = NULL;
2378
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002379 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002380 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002381 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002382 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002383 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002384 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002385 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00002386 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002387 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00002388 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002389
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002390 /* Expand the rest into (possibly) many strings each */
2391 argv_expanded = expand_strvec_to_strvec(argv + i);
2392
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002393 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002394 if (strcmp(argv_expanded[0], x->cmd) != 0)
2395 continue;
2396 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2397 debug_printf("exec with redirects only\n");
2398 setup_redirects(command, NULL);
2399 rcode = EXIT_SUCCESS;
2400 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00002401 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002402 debug_printf("builtin inline %s\n", argv_expanded[0]);
2403 /* XXX setup_redirects acts on file descriptors, not FILEs.
2404 * This is perfect for work that comes after exec().
2405 * Is it really safe for inline use? Experimentally,
2406 * things seem to work with glibc. */
2407 setup_redirects(command, squirrel);
2408 new_env = expand_assignments(argv, command->assignment_cnt);
2409 old_env = putenv_all_and_save_old(new_env);
2410 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2411 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002412#if ENABLE_FEATURE_SH_STANDALONE
2413 clean_up_and_ret:
2414#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002415 restore_redirects(squirrel);
2416 free_strings_and_unsetenv(new_env, 1);
2417 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002418 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002419 clean_up_and_ret1:
2420 free(argv_expanded);
2421 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2422 debug_printf_exec("run_pipe return %d\n", rcode);
2423 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002424 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002425#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002426 i = find_applet_by_name(argv_expanded[0]);
2427 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2428 setup_redirects(command, squirrel);
2429 save_nofork_data(&G.nofork_save);
2430 new_env = expand_assignments(argv, command->assignment_cnt);
2431 old_env = putenv_all_and_save_old(new_env);
2432 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2433 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2434 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002435 }
2436#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002437 }
2438
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002439 /* NB: argv_expanded may already be created, and that
2440 * might include `cmd` runs! Do not rerun it! We *must*
2441 * use argv_expanded if it's non-NULL */
2442
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002443 /* Disable job control signals for shell (parent) and
2444 * for initial child code after fork */
2445 set_jobctrl_sighandler(SIG_IGN);
2446
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002447 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002448 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002449 nextin = 0;
2450
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002451 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00002452#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002453 volatile nommu_save_t nommu_save;
2454 nommu_save.new_env = NULL;
2455 nommu_save.old_env = NULL;
2456 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002457#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002458 command = &(pi->cmds[i]);
2459 if (command->argv) {
2460 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002461 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002462 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002463
2464 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002465 pipefds[0] = 0;
2466 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002467 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002468 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00002469
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002470 command->pid = BB_MMU ? fork() : vfork();
2471 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00002472 if (ENABLE_HUSH_JOB)
2473 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002474#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002475 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00002476 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002477 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002478 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002479 /* Don't do pgrp restore anymore on fatal signals */
2480 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002481 pgrp = pi->pgrp;
2482 if (pgrp < 0) /* true for 1st process only */
2483 pgrp = getpid();
2484 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002485 /* We do it in *every* child, not just first,
2486 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002487 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002488 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002489 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002490#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00002491 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002492 xmove_fd(pipefds[1], 1); /* write end */
2493 if (pipefds[0] > 1)
2494 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00002495 /* Like bash, explicit redirects override pipes,
2496 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002497 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00002498
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002499 /* Restore default handlers just prior to exec */
2500 set_jobctrl_sighandler(SIG_DFL);
2501 set_misc_sighandler(SIG_DFL);
2502 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002503 /* Stores to nommu_save list of env vars putenv'ed
2504 * (NOMMU, on MMU we don't need that) */
2505 /* cast away volatility... */
2506 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002507 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002508 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002509 /* parent */
2510#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002511 /* Clean up after vforked child */
2512 free(nommu_save.argv);
2513 free_strings_and_unsetenv(nommu_save.new_env, 1);
2514 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002515#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002516 free(argv_expanded);
2517 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002518 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002519 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002520 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002521 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002522 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002523#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002524 /* Second and next children need to know pid of first one */
2525 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002526 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002527#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002528 }
Eric Andersen25f27032001-04-26 23:22:31 +00002529
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002530 if (i)
2531 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002532 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002533 close(pipefds[1]); /* write end */
2534 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002535 nextin = pipefds[0];
2536 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002537
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002538 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002539 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2540 return 1;
2541 }
2542
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002543 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002544 return -1;
2545}
2546
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002547#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002548static void debug_print_tree(struct pipe *pi, int lvl)
2549{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002550 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002551 [PIPE_SEQ] = "SEQ",
2552 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002553 [PIPE_OR ] = "OR" ,
2554 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002555 };
2556 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002557 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002558#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002559 [RES_IF ] = "IF" ,
2560 [RES_THEN ] = "THEN" ,
2561 [RES_ELIF ] = "ELIF" ,
2562 [RES_ELSE ] = "ELSE" ,
2563 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002564#endif
2565#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002566 [RES_FOR ] = "FOR" ,
2567 [RES_WHILE] = "WHILE",
2568 [RES_UNTIL] = "UNTIL",
2569 [RES_DO ] = "DO" ,
2570 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002571#endif
2572#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002573 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002574#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002575#if ENABLE_HUSH_CASE
2576 [RES_CASE ] = "CASE" ,
2577 [RES_MATCH] = "MATCH",
2578 [RES_CASEI] = "CASEI",
2579 [RES_ESAC ] = "ESAC" ,
2580#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002581 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002582 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002583 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002584 static const char *const GRPTYPE[] = {
2585 "()",
2586 "{}",
2587#if ENABLE_HUSH_FUNCTIONS
2588 "func()",
2589#endif
2590 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002591
2592 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002593
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002594 pin = 0;
2595 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002596 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2597 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002598 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002599 while (prn < pi->num_cmds) {
2600 struct command *command = &pi->cmds[prn];
2601 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002602
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002603 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2604 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002605 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002606 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002607 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002608 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002609 prn++;
2610 continue;
2611 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002612 if (argv) while (*argv) {
2613 fprintf(stderr, " '%s'", *argv);
2614 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002615 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002616 fprintf(stderr, "\n");
2617 prn++;
2618 }
2619 pi = pi->next;
2620 pin++;
2621 }
2622}
2623#endif
2624
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002625/* NB: called by pseudo_exec, and therefore must not modify any
2626 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002627static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002628{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002629#if ENABLE_HUSH_CASE
2630 char *case_word = NULL;
2631#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002632#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002633 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002634 char *for_varname = NULL;
2635 char **for_lcur = NULL;
2636 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002637#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002638 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002639 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002640#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002641 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002642#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002643 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002644#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002645 /*enum reserved_style*/ smallint rword = RES_NONE;
2646 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002647
Denis Vlasenko87a86552008-07-29 19:43:10 +00002648 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002649
Denis Vlasenko06810332007-05-21 23:30:54 +00002650#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002651 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002652 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2653 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002654 continue;
2655 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002656 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002657 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002658 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002659 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002660 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002661 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002662 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002663 continue;
2664 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002665 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2666 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002667 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002668 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002669 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002670 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002671 }
2672 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002673#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002674
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002675 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002676 * in order to return, no direct "return" statements please.
2677 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002678
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002679#if ENABLE_HUSH_JOB
2680 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2681 * We are saving state before entering outermost list ("while...done")
2682 * so that ctrl-Z will correctly background _entire_ outermost list,
2683 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002684 if (++G.run_list_level == 1 && G.interactive_fd) {
2685 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002686 /* ctrl-Z forked and we are parent; or ctrl-C.
2687 * Sighandler has longjmped us here */
2688 signal(SIGINT, SIG_IGN);
2689 signal(SIGTSTP, SIG_IGN);
2690 /* Restore level (we can be coming from deep inside
2691 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002692 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002693#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002694 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002695 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002696 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002697 }
2698#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002699 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002700 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2701 * Remember this child as background job */
2702 insert_bg_job(pi);
2703 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002704 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002705 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002706 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002707 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002708 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002709 rcode = 0;
2710 goto ret;
2711 }
2712 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002713 G.toplevel_list = pi;
2714 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002715#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002716 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002717#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002718 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002719 signal(SIGINT, handler_ctrl_c);
2720 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002721#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002722
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002723 /* Go through list of pipes, (maybe) executing them. */
2724 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002725 IF_HAS_KEYWORDS(rword = pi->res_word;)
2726 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002727 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2728 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002729#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002730 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002731 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002732 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002733 /* start of a loop: remember where loop starts */
2734 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002735 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002736 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002737#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002738 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002739 if (pi->followup == PIPE_SEQ)
2740 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002741 /* it is "<false> && CMD" or "<true> || CMD"
2742 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002743 continue;
2744 }
2745 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002746 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002747#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002748 if (cond_code) {
2749 if (rword == RES_THEN) {
2750 /* "if <false> THEN cmd": skip cmd */
2751 continue;
2752 }
2753 } else {
2754 if (rword == RES_ELSE || rword == RES_ELIF) {
2755 /* "if <true> then ... ELSE/ELIF cmd":
2756 * skip cmd and all following ones */
2757 break;
2758 }
2759 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002760#endif
2761#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002762 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002763 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002764 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002765
2766 static const char encoded_dollar_at[] ALIGN1 = {
2767 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2768 }; /* encoded representation of "$@" */
2769 static const char *const encoded_dollar_at_argv[] = {
2770 encoded_dollar_at, NULL
2771 }; /* argv list with one element: "$@" */
2772 char **vals;
2773
2774 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002775 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002776 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002777 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002778 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002779 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002780 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002781 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002782 debug_print_strings("for_list made from", vals);
2783 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002784 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002785 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002786 for_varname = pi->cmds[0].argv[0];
2787 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002788 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002789 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002790 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002791 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002792 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002793 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002794 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002795 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002796 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002797 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002798 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002799//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002800 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2801 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002802 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002803 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002804 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002805 if (rword == RES_DONE) {
2806 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002807 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002808#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002809#if ENABLE_HUSH_CASE
2810 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002811 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002812 continue;
2813 }
2814 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002815 char **argv;
2816
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002817 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2818 break;
2819 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002820 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002821 while (*argv) {
2822 char *pattern = expand_string_to_string(*argv);
2823 /* TODO: which FNM_xxx flags to use? */
2824 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2825 free(pattern);
2826 if (cond_code == 0) { /* match! we will execute this branch */
2827 free(case_word); /* make future "word)" stop */
2828 case_word = NULL;
2829 break;
2830 }
2831 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002832 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002833 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002834 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002835 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002836 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002837 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002838 }
2839#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002840 if (pi->num_cmds == 0)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002841 continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002842
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002843 /* After analyzing all keywords and conditions, we decided
2844 * to execute this pipe. NB: has to do checkjobs(NULL)
2845 * after run_pipe() to collect any background children,
2846 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002847 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002848 {
2849 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002850#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002851 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002852#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002853 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2854 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002855 /* we only ran a builtin: rcode is already known
2856 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002857#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002858 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002859 if (G.flag_break_continue) {
2860 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002861 /* we might fall into outer *loop*,
2862 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002863 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002864 G.depth_break_continue--;
2865 if (G.depth_break_continue == 0)
2866 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002867 /* else: e.g. "continue 2" should *break* once, *then* continue */
2868 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002869 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002870 goto check_jobs_and_break;
2871 /* "continue": simulate end of loop */
2872 rword = RES_DONE;
2873 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002874 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002875#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002876 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002877 /* what does bash do with attempts to background builtins? */
2878 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002879 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2880 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002881#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002882 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002883 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002884#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002885 rcode = 0; /* EXIT_SUCCESS */
2886 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002887#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002888 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002889 /* waits for completion, then fg's main shell */
2890 rcode = checkjobs_and_fg_shell(pi);
2891 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2892 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002893#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002894 { /* this one just waits for completion */
2895 rcode = checkjobs(pi);
2896 debug_printf_exec(": checkjobs returned %d\n", rcode);
2897 }
Eric Andersen25f27032001-04-26 23:22:31 +00002898 }
2899 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002900 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002901 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002902
2903 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002904#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002905 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002906 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002907#endif
2908#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002909 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002910 if (rcode) {
2911 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002912 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002913 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002914 }
2915 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002916 if (!rcode) {
2917 check_jobs_and_break:
2918 checkjobs(NULL);
2919 break;
2920 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002921 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002922#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002923 if ((rcode == 0 && pi->followup == PIPE_OR)
2924 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002925 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002926 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002927 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002928 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002929 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002930
2931#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002932 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002933 /* ctrl-Z forked somewhere in the past, we are the child,
2934 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002935//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002936 exit(rcode);
2937 }
2938 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002939 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002940 signal(SIGTSTP, SIG_IGN);
2941 signal(SIGINT, SIG_IGN);
2942 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002943#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002944 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002945#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002946 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002947 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002948 free(for_list);
2949#endif
2950#if ENABLE_HUSH_CASE
2951 free(case_word);
2952#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002953 return rcode;
2954}
2955
Eric Andersen25f27032001-04-26 23:22:31 +00002956/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002957static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002958{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002959 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002960 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002961 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002962 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002963 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002964 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002965 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002966 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002967 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002968 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002969 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002970 return rcode;
2971}
2972
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002973
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002974/* Peek ahead in the in_str to find out if we have a "&n" construct,
2975 * as in "2>&1", that represents duplicating a file descriptor.
2976 * Return either -2 (syntax error), -1 (no &), or the number found.
2977 */
2978static int redirect_dup_num(struct in_str *input)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002979{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002980 int ch, d = 0, ok = 0;
2981 ch = i_peek(input);
2982 if (ch != '&') return -1;
2983
2984 i_getch(input); /* get the & */
2985 ch = i_peek(input);
2986 if (ch == '-') {
2987 i_getch(input);
2988 return -3; /* "-" represents "close me" */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002989 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002990 while (isdigit(ch)) {
2991 d = d*10 + (ch-'0');
2992 ok = 1;
2993 i_getch(input);
2994 ch = i_peek(input);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002995 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996 if (ok) return d;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002997
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002998 bb_error_msg("ambiguous redirect");
2999 return -2;
Eric Andersen78a7c992001-05-15 16:30:25 +00003000}
3001
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003002/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00003003 * for file descriptor duplication, e.g., "2>&1".
3004 * Return code is 0 normally, 1 if a syntax error is detected in src.
3005 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003006static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00003007 struct in_str *input)
3008{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003009 struct command *command = ctx->command;
3010 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003011 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003012
3013 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003014 while (redir) {
3015 last_redir = redir;
3016 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00003017 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003018 redir = xzalloc(sizeof(struct redir_struct));
3019 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003020 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00003021 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003022 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003023 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003024 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003025 }
3026
Denis Vlasenko55789c62008-06-18 16:30:42 +00003027 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003028 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00003029
3030 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3031
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003032 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00003033 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003034 if (redir->dup == -2)
3035 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00003036 if (redir->dup != -1) {
3037 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00003038 * is legit; I postpone that to "run time"
3039 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00003040 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3041 } else {
3042 /* We do _not_ try to open the file that src points to,
3043 * since we need to return and let src be expanded first.
3044 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00003045 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00003046 ctx->pending_redirect = redir;
3047 }
3048 return 0;
3049}
3050
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003051
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003052static struct pipe *new_pipe(void)
3053{
Eric Andersen25f27032001-04-26 23:22:31 +00003054 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003055 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003056 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003057 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003058 return pi;
3059}
3060
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003061/* Command (member of a pipe) is complete. The only possible error here
3062 * is out of memory, in which case xmalloc exits. */
3063static int done_command(struct parse_context *ctx)
3064{
3065 /* The command is really already in the pipe structure, so
3066 * advance the pipe counter and make a new, null command. */
3067 struct pipe *pi = ctx->pipe;
3068 struct command *command = ctx->command;
3069
3070 if (command) {
3071 if (command->group == NULL
3072 && command->argv == NULL
3073 && command->redirects == NULL
3074 ) {
3075 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3076 return pi->num_cmds;
3077 }
3078 pi->num_cmds++;
3079 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3080 } else {
3081 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3082 }
3083
3084 /* Only real trickiness here is that the uncommitted
3085 * command structure is not counted in pi->num_cmds. */
3086 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3087 command = &pi->cmds[pi->num_cmds];
3088 memset(command, 0, sizeof(*command));
3089
3090 ctx->command = command;
3091 /* but ctx->pipe and ctx->list_head remain unchanged */
3092
3093 return pi->num_cmds; /* used only for 0/nonzero check */
3094}
3095
3096static void done_pipe(struct parse_context *ctx, pipe_style type)
3097{
3098 int not_null;
3099
3100 debug_printf_parse("done_pipe entered, followup %d\n", type);
3101 /* Close previous command */
3102 not_null = done_command(ctx);
3103 ctx->pipe->followup = type;
3104 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3105 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3106 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3107
3108 /* Without this check, even just <enter> on command line generates
3109 * tree of three NOPs (!). Which is harmless but annoying.
3110 * IOW: it is safe to do it unconditionally.
3111 * RES_NONE case is for "for a in; do ..." (empty IN set)
3112 * to work, possibly other cases too. */
3113 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3114 struct pipe *new_p;
3115 debug_printf_parse("done_pipe: adding new pipe: "
3116 "not_null:%d ctx->ctx_res_w:%d\n",
3117 not_null, ctx->ctx_res_w);
3118 new_p = new_pipe();
3119 ctx->pipe->next = new_p;
3120 ctx->pipe = new_p;
3121 ctx->command = NULL; /* needed! */
3122 /* RES_THEN, RES_DO etc are "sticky" -
3123 * they remain set for commands inside if/while.
3124 * This is used to control execution.
3125 * RES_FOR and RES_IN are NOT sticky (needed to support
3126 * cases where variable or value happens to match a keyword):
3127 */
3128#if ENABLE_HUSH_LOOPS
3129 if (ctx->ctx_res_w == RES_FOR
3130 || ctx->ctx_res_w == RES_IN)
3131 ctx->ctx_res_w = RES_NONE;
3132#endif
3133#if ENABLE_HUSH_CASE
3134 if (ctx->ctx_res_w == RES_MATCH)
3135 ctx->ctx_res_w = RES_CASEI;
3136#endif
3137 /* Create the memory for command, roughly:
3138 * ctx->pipe->cmds = new struct command;
3139 * ctx->command = &ctx->pipe->cmds[0];
3140 */
3141 done_command(ctx);
3142 }
3143 debug_printf_parse("done_pipe return\n");
3144}
3145
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003146static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003147{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003148 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003149 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003150 /* Create the memory for command, roughly:
3151 * ctx->pipe->cmds = new struct command;
3152 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003153 */
3154 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003155}
3156
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003157
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003158/* If a reserved word is found and processed, parse context is modified
3159 * and 1 is returned.
3160 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003161 * case, function, and select are obnoxious, save those for later.
3162 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003163#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003164struct reserved_combo {
3165 char literal[6];
3166 unsigned char res;
3167 unsigned char assignment_flag;
3168 int flag;
3169};
3170enum {
3171 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003172#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003173 FLAG_IF = (1 << RES_IF ),
3174 FLAG_THEN = (1 << RES_THEN ),
3175 FLAG_ELIF = (1 << RES_ELIF ),
3176 FLAG_ELSE = (1 << RES_ELSE ),
3177 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003178#endif
3179#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003180 FLAG_FOR = (1 << RES_FOR ),
3181 FLAG_WHILE = (1 << RES_WHILE),
3182 FLAG_UNTIL = (1 << RES_UNTIL),
3183 FLAG_DO = (1 << RES_DO ),
3184 FLAG_DONE = (1 << RES_DONE ),
3185 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003186#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003187#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003188 FLAG_MATCH = (1 << RES_MATCH),
3189 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003190#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003191 FLAG_START = (1 << RES_XXXX ),
3192};
3193
3194static const struct reserved_combo* match_reserved_word(o_string *word)
3195{
Eric Andersen25f27032001-04-26 23:22:31 +00003196 /* Mostly a list of accepted follow-up reserved words.
3197 * FLAG_END means we are done with the sequence, and are ready
3198 * to turn the compound list into a command.
3199 * FLAG_START means the word must start a new compound list.
3200 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003201 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003202#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003203 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3204 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3205 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3206 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3207 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3208 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003209#endif
3210#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003211 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3212 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3213 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3214 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3215 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3216 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003217#endif
3218#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003219 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3220 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003221#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003222 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003223 const struct reserved_combo *r;
3224
3225 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3226 if (strcmp(word->data, r->literal) == 0)
3227 return r;
3228 }
3229 return NULL;
3230}
3231static int reserved_word(o_string *word, struct parse_context *ctx)
3232{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003233#if ENABLE_HUSH_CASE
3234 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003235 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003236 };
3237#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003238 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003239
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003240 r = match_reserved_word(word);
3241 if (!r)
3242 return 0;
3243
3244 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003245#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003246 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3247 /* "case word IN ..." - IN part starts first match part */
3248 r = &reserved_match;
3249 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003250#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003251 if (r->flag == 0) { /* '!' */
3252 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003253 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003254 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003255 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003256 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003257 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003258 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003259 if (r->flag & FLAG_START) {
3260 struct parse_context *new;
3261 debug_printf("push stack\n");
3262 new = xmalloc(sizeof(*new));
3263 *new = *ctx; /* physical copy */
3264 initialize_context(ctx);
3265 ctx->stack = new;
3266 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3267 syntax(NULL);
3268 ctx->ctx_res_w = RES_SNTX;
3269 return 1;
3270 }
3271 ctx->ctx_res_w = r->res;
3272 ctx->old_flag = r->flag;
3273 if (ctx->old_flag & FLAG_END) {
3274 struct parse_context *old;
3275 debug_printf("pop stack\n");
3276 done_pipe(ctx, PIPE_SEQ);
3277 old = ctx->stack;
3278 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003279 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003280 *ctx = *old; /* physical copy */
3281 free(old);
3282 }
3283 word->o_assignment = r->assignment_flag;
3284 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003285}
Denis Vlasenko06810332007-05-21 23:30:54 +00003286#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003287
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003288//TODO: many, many callers don't check error from done_word()
3289
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003290/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003291 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003292static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003293{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003294 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003295
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003296 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003297 if (word->length == 0 && word->nonnull == 0) {
3298 debug_printf_parse("done_word return 0: true null, ignored\n");
3299 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003300 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003301 /* If this word wasn't an assignment, next ones definitely
3302 * can't be assignments. Even if they look like ones. */
3303 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3304 && word->o_assignment != WORD_IS_KEYWORD
3305 ) {
3306 word->o_assignment = NOT_ASSIGNMENT;
3307 } else {
3308 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003309 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003310 word->o_assignment = MAYBE_ASSIGNMENT;
3311 }
3312
Eric Andersen25f27032001-04-26 23:22:31 +00003313 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003314 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3315 * only if run as "bash", not "sh" */
3316 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003317 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003318 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003319 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003320 /* "{ echo foo; } echo bar" - bad */
3321 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003322 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003323 syntax(NULL);
3324 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3325 return 1;
3326 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003327#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003328#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003329 if (ctx->ctx_dsemicolon
3330 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3331 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003332 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003333 /* ctx->ctx_res_w = RES_MATCH; */
3334 ctx->ctx_dsemicolon = 0;
3335 } else
3336#endif
3337
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003338 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003339#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003340 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3341 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003342#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003343 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003344 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3345 if (reserved_word(word, ctx)) {
3346 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003347 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3348 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003349 }
Eric Andersen25f27032001-04-26 23:22:31 +00003350 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003351#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003352 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003353 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3354 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003355 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003356 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003357 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003358 char *p = word->data;
3359 while (p[0] == SPECIAL_VAR_SYMBOL
3360 && (p[1] & 0x7f) == '@'
3361 && p[2] == SPECIAL_VAR_SYMBOL
3362 ) {
3363 p += 3;
3364 }
3365 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003366 /* saw no "$@", or not only "$@" but some
3367 * real text is there too */
3368 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003369 * e.g. "", $empty"" etc to not disappear */
3370 o_addchr(word, SPECIAL_VAR_SYMBOL);
3371 o_addchr(word, SPECIAL_VAR_SYMBOL);
3372 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003373 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003374 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003375 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003376 }
Eric Andersen25f27032001-04-26 23:22:31 +00003377
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003378 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003379 ctx->pending_redirect = NULL;
3380
Denis Vlasenko06810332007-05-21 23:30:54 +00003381#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003382 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003383 /* NB: basically, this makes hush see "for v in ..." syntax as if
3384 * as it is "for v; in ...". FOR and IN become two pipe structs
3385 * in parse tree. */
3386 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003387//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003388 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003389 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003390#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003391#if ENABLE_HUSH_CASE
3392 /* Force CASE to have just one word */
3393 if (ctx->ctx_res_w == RES_CASE) {
3394 done_pipe(ctx, PIPE_SEQ);
3395 }
3396#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003397 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003398 return 0;
3399}
3400
Eric Andersen25f27032001-04-26 23:22:31 +00003401/* If a redirect is immediately preceded by a number, that number is
3402 * supposed to tell which file descriptor to redirect. This routine
3403 * looks for such preceding numbers. In an ideal world this routine
3404 * needs to handle all the following classes of redirects...
3405 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3406 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3407 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3408 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3409 * A -1 output from this program means no valid number was found, so the
3410 * caller should use the appropriate default for this redirection.
3411 */
3412static int redirect_opt_num(o_string *o)
3413{
3414 int num;
3415
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003416 if (o->length == 0)
3417 return -1;
3418 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003419 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003420 return -1;
3421 }
3422 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003423 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003424 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003425 return num;
3426}
3427
Mike Frysingerddbee972009-03-22 22:48:41 +00003428static int parse_stream(o_string *dest, struct parse_context *ctx,
3429 struct in_str *input0, const char *end_trigger);
3430
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003431#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003432static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003433{
3434 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003435 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003436
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003437 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003438/* *** NOMMU WARNING *** */
3439/* By using vfork here, we suspend parent till child exits or execs.
3440 * If child will not do it before it fills the pipe, it can block forever
3441 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003442 * Try this script:
3443 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3444 * huge=`cat TESTFILE` # will block here forever
3445 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003446 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003447 pid = BB_MMU ? fork() : vfork();
3448 if (pid < 0)
3449 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003450 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003451 if (ENABLE_HUSH_JOB)
3452 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003453 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003454 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003455 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003456#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003457 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003458#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003459 /* Process substitution is not considered to be usual
3460 * 'command execution'.
3461 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3462 /* Not needed, we are relying on it being disabled
3463 * everywhere outside actual command execution. */
3464 /*set_jobctrl_sighandler(SIG_IGN);*/
3465 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003466 /* Freeing 'head' here would break NOMMU. */
3467 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003468 }
Eric Andersen25f27032001-04-26 23:22:31 +00003469 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003470 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003471 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003472 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003473}
3474
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003475/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003476static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003477 struct in_str *input,
3478 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003479{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003480 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003481 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003482 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003483 FILE *p;
3484 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003485
Eric Andersen25f27032001-04-26 23:22:31 +00003486 initialize_context(&inner);
3487
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003488 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003489 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003490 if (retcode != 0)
3491 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003492 done_word(&result, &inner);
3493 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003494 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003495
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003496 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003497 if (p == NULL)
3498 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003499 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003500 setup_file_in_str(&pipe_str, p);
3501
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003502 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003503 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003504 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003505 if (ch == '\n') {
3506 eol_cnt++;
3507 continue;
3508 }
3509 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003510 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003511 eol_cnt--;
3512 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003513 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003514 }
3515
3516 debug_printf("done reading from pipe, pclose()ing\n");
3517 /* This is the step that wait()s for the child. Should be pretty
3518 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003519 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003520 * at the same time. That would be a lot of work, and contrary
3521 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003522 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003523 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003524 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003525 return retcode;
3526}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003527#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003528
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003529static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003530 struct in_str *input, int ch)
3531{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003532 /* dest contains characters seen prior to ( or {.
3533 * Typically it's empty, but for functions defs,
3534 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003535 int rcode;
3536 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003537 struct parse_context sub;
3538 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003539
3540 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003541#if ENABLE_HUSH_FUNCTIONS
3542 if (ch == 'F') { /* function definition? */
3543 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3544 //command->fname = dest->data;
3545 command->grp_type = GRP_FUNCTION;
3546//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3547 memset(dest, 0, sizeof(*dest));
3548 }
3549#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003550 if (command->argv /* word [word](... */
3551 || dest->length /* word(... */
3552 || dest->nonnull /* ""(... */
3553 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003554 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003555 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3556 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003557 }
3558 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003559 endch = "}";
3560 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003561 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003562 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003563 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003564 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003565 if (rcode == 0) {
3566 done_word(dest, &sub); /* finish off the final word in the subcontext */
3567 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003568 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003569 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003570 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003571 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003572 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003573}
3574
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003575#if ENABLE_HUSH_TICK
3576/* Subroutines for copying $(...) and `...` things */
3577static void add_till_backquote(o_string *dest, struct in_str *input);
3578/* '...' */
3579static void add_till_single_quote(o_string *dest, struct in_str *input)
3580{
3581 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003582 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003583 if (ch == EOF)
3584 break;
3585 if (ch == '\'')
3586 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003587 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003588 }
3589}
3590/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3591static void add_till_double_quote(o_string *dest, struct in_str *input)
3592{
3593 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003594 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003595 if (ch == '"')
3596 break;
3597 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003598 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003599 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003600 }
3601 if (ch == EOF)
3602 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003603 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003604 if (ch == '`') {
3605 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003606 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003607 continue;
3608 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003609 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003610 }
3611}
3612/* Process `cmd` - copy contents until "`" is seen. Complicated by
3613 * \` quoting.
3614 * "Within the backquoted style of command substitution, backslash
3615 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3616 * The search for the matching backquote shall be satisfied by the first
3617 * backquote found without a preceding backslash; during this search,
3618 * if a non-escaped backquote is encountered within a shell comment,
3619 * a here-document, an embedded command substitution of the $(command)
3620 * form, or a quoted string, undefined results occur. A single-quoted
3621 * or double-quoted string that begins, but does not end, within the
3622 * "`...`" sequence produces undefined results."
3623 * Example Output
3624 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3625 */
3626static void add_till_backquote(o_string *dest, struct in_str *input)
3627{
3628 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003629 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003630 if (ch == '`')
3631 break;
3632 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003633 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003634 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003635 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003636 ch = ch2;
3637 }
3638 if (ch == EOF)
3639 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003640 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003641 }
3642}
3643/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3644 * quoting and nested ()s.
3645 * "With the $(command) style of command substitution, all characters
3646 * following the open parenthesis to the matching closing parenthesis
3647 * constitute the command. Any valid shell script can be used for command,
3648 * except a script consisting solely of redirections which produces
3649 * unspecified results."
3650 * Example Output
3651 * echo $(echo '(TEST)' BEST) (TEST) BEST
3652 * echo $(echo 'TEST)' BEST) TEST) BEST
3653 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3654 */
3655static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3656{
3657 int count = 0;
3658 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003659 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003660 if (ch == EOF)
3661 break;
3662 if (ch == '(')
3663 count++;
3664 if (ch == ')')
3665 if (--count < 0)
3666 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003667 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003668 if (ch == '\'') {
3669 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003670 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003671 continue;
3672 }
3673 if (ch == '"') {
3674 add_till_double_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 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003678 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3679 ch = i_getch(input);
3680 if (ch == EOF)
3681 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003682 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003683 continue;
3684 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003685 }
3686}
3687#endif /* ENABLE_HUSH_TICK */
3688
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003689/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003690static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003691{
Mike Frysinger6379bb42009-03-28 18:55:03 +00003692 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003693 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003694 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003695
3696 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003697 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003698 i_getch(input);
3699 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003701 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003702 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003703 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003704 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003705 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003706 if (!isalnum(ch) && ch != '_')
3707 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003708 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003709 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003710 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003711 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003712 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003713 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003714 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003715 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003716 o_addchr(dest, ch | quote_mask);
3717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003718 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003719 case '$': /* pid */
3720 case '!': /* last bg pid */
3721 case '?': /* last exit code */
3722 case '#': /* number of args */
3723 case '*': /* args */
3724 case '@': /* args */
3725 goto make_one_char_var;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003726 case '{': {
3727 bool first_char;
3728
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003729 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3730 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003731 /* XXX maybe someone will try to escape the '}' */
Mike Frysinger6379bb42009-03-28 18:55:03 +00003732 expansion = 0;
3733 first_char = true;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003734 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003735 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003736 if (ch == '}')
3737 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003738
3739 if (ch == '#' && first_char)
3740 /* ${#var}: length of var contents */;
3741
3742 else if (expansion < 2 && !isalnum(ch) && ch != '_') {
3743 /* handle parameter expansions
3744 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3745 */
3746 if (first_char)
3747 goto case_default;
3748 switch (ch) {
3749 case ':': /* null modifier */
3750 if (expansion == 0) {
3751 debug_printf_parse(": null modifier\n");
3752 ++expansion;
3753 break;
3754 }
3755 goto case_default;
3756
3757#if 0 /* not implemented yet :( */
3758 case '#': /* remove prefix */
3759 case '%': /* remove suffix */
3760 if (expansion == 0) {
3761 debug_printf_parse(": remove suffix/prefix\n");
3762 expansion = 2;
3763 break;
3764 }
3765 goto case_default;
3766#endif
3767
3768 case '-': /* default value */
3769 case '=': /* assign default */
3770 case '+': /* alternative */
3771 case '?': /* error indicate */
3772 debug_printf_parse(": parameter expansion\n");
3773 expansion = 2;
3774 break;
3775
3776 default:
3777 case_default:
3778 syntax("unterminated ${name}");
3779 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3780 return 1;
3781 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003782 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003783 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003784 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003785 quote_mask = 0;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003786 first_char = false;
Eric Andersen25f27032001-04-26 23:22:31 +00003787 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003788 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003789 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003790 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003791#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003792 case '(': {
3793 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003794 i_getch(input);
3795 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3796 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003797 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003798 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003800 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003801 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003802#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003803 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003804 i_getch(input);
3805 ch = i_peek(input);
3806 if (isalnum(ch)) { /* it's $_name or $_123 */
3807 ch = '_';
3808 goto make_var;
3809 }
3810 /* else: it's $_ */
3811 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003812 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003813 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003814 return 1;
3815 break;
3816 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003817 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003818 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003819 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003820 return 0;
3821}
3822
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003823/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003824 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3825 * Return code is 0 if end_trigger char is met,
3826 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003827 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003828static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003829 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003830{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003831 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003832 int redir_fd;
3833 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003834 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003835 int next;
3836
Denis Vlasenkoff097622007-10-01 10:00:45 +00003837 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003838 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003839 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003840
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003841 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 +00003842
Denis Vlasenko1a735862007-05-23 00:32:25 +00003843 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003844 m = CHAR_IFS;
3845 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003846 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003847 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003848 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003849 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003850 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003851 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003852 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003853 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003854 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003855 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003856 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003857 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003858 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003859 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003860 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3861 return 1;
3862 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003863 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003864 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3865 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003866 && ch == '='
3867 && is_assignment(dest->data)
3868 ) {
3869 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3870 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003871 continue;
3872 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003873 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003874 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003875 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003876 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003877 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003878 if (ch == EOF)
3879 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003880 /* If we aren't performing a substitution, treat
3881 * a newline as a command separator.
3882 * [why we don't handle it exactly like ';'? --vda] */
3883 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003884#if ENABLE_HUSH_CASE
3885 /* "case ... in <newline> word) ..." -
3886 * newlines are ignored (but ';' wouldn't be) */
3887 if (dest->length == 0 // && argv[0] == NULL
3888 && ctx->ctx_res_w == RES_MATCH
3889 ) {
3890 continue;
3891 }
3892#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003893 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003894 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003895 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003896 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003897 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003898 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003899 /* Special case: (...word) makes last word terminate,
3900 * as if ';' is seen */
3901 if (ch == ')') {
3902 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003903//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003904 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003905 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003906 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003907 if (!HAS_KEYWORDS
3908 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3909 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003910 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3911 return 0;
3912 }
3913 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003914 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003915 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003916 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003917
3918 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3919 /* ch is a special char and thus this word
3920 * cannot be an assignment: */
3921 dest->o_assignment = NOT_ASSIGNMENT;
3922 }
3923
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003924 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003925 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003926 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003927 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003928 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003929 if (ch == EOF || ch == '\n')
3930 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003931 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003932 }
Eric Andersen25f27032001-04-26 23:22:31 +00003933 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003934 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003935 }
3936 break;
3937 case '\\':
3938 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003939 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003940 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003941 return 1;
3942 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003943 /* bash:
3944 * "The backslash retains its special meaning [in "..."]
3945 * only when followed by one of the following characters:
3946 * $, `, ", \, or <newline>. A double quote may be quoted
3947 * within double quotes by preceding it with a backslash.
3948 * If enabled, history expansion will be performed unless
3949 * an ! appearing in double quotes is escaped using
3950 * a backslash. The backslash preceding the ! is not removed."
3951 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003952 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003953 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003954 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003955 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003956 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003957 }
3958 } else {
3959 o_addchr(dest, '\\');
3960 o_addchr(dest, i_getch(input));
3961 }
Eric Andersen25f27032001-04-26 23:22:31 +00003962 break;
3963 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003964 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003965 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3966 return 1;
3967 }
Eric Andersen25f27032001-04-26 23:22:31 +00003968 break;
3969 case '\'':
3970 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003971 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003972 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003973 if (ch == EOF) {
3974 syntax("unterminated '");
3975 debug_printf_parse("parse_stream return 1: unterminated '\n");
3976 return 1;
3977 }
3978 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003979 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003980 if (dest->o_assignment == NOT_ASSIGNMENT)
3981 o_addqchr(dest, ch);
3982 else
3983 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003984 }
Eric Andersen25f27032001-04-26 23:22:31 +00003985 break;
3986 case '"':
3987 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003988 shadow_quote ^= 1; /* invert */
3989 if (dest->o_assignment == NOT_ASSIGNMENT)
3990 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003991 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003992#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003993 case '`': {
3994 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003995 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003996 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003997 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003998 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003999 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004000 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004001 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004002#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004003 case '>':
4004 redir_fd = redirect_opt_num(dest);
4005 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004006 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00004007 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004008 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004009 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004010 }
4011#if 0
4012 else if (next == '(') {
4013 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004014 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004015 return 1;
4016 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004017#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004018 setup_redirect(ctx, redir_fd, redir_style, input);
4019 break;
4020 case '<':
4021 redir_fd = redirect_opt_num(dest);
4022 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004023 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00004024 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004025 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004026 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004027 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004028 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004029 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004030 }
4031#if 0
4032 else if (next == '(') {
4033 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004034 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004035 return 1;
4036 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004037#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004038 setup_redirect(ctx, redir_fd, redir_style, input);
4039 break;
4040 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004041#if ENABLE_HUSH_CASE
4042 case_semi:
4043#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004044 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004045 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004046#if ENABLE_HUSH_CASE
4047 /* Eat multiple semicolons, detect
4048 * whether it means something special */
4049 while (1) {
4050 ch = i_peek(input);
4051 if (ch != ';')
4052 break;
4053 i_getch(input);
4054 if (ctx->ctx_res_w == RES_CASEI) {
4055 ctx->ctx_dsemicolon = 1;
4056 ctx->ctx_res_w = RES_MATCH;
4057 break;
4058 }
4059 }
4060#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004061 new_cmd:
4062 /* We just finished a cmd. New one may start
4063 * with an assignment */
4064 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004065 break;
4066 case '&':
4067 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004068 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004069 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004070 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004071 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004072 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004073 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004074 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004075 case '|':
4076 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004077#if ENABLE_HUSH_CASE
4078 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004079 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004080#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004081 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004082 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004083 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004084 } else {
4085 /* we could pick up a file descriptor choice here
4086 * with redirect_opt_num(), but bash doesn't do it.
4087 * "echo foo 2| cat" yields "foo 2". */
4088 done_command(ctx);
4089 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004090 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004091 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004092#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004093 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004094 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004095 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004096 && dest->length == 0 /* not word(... */
4097 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004098 ) {
4099 continue;
4100 }
4101#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004102#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004103 if (dest->length != 0 /* not just () but word() */
4104 && dest->nonnull == 0 /* not a"b"c() */
4105 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004106//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004107 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004108 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004109 ) {
4110 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004111 i_getch(input);
4112 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004113//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004114 ch = i_getch(input);
4115 } while (ch == ' ' || ch == '\n');
4116 if (ch != '{') {
4117 syntax("was expecting {");
4118 debug_printf_parse("parse_stream return 1\n");
4119 return 1;
4120 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004121 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004122 }
4123#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004124 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004125 if (parse_group(dest, ctx, input, ch) != 0) {
4126 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004127 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004128 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004129 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004130 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004131#if ENABLE_HUSH_CASE
4132 if (ctx->ctx_res_w == RES_MATCH)
4133 goto case_semi;
4134#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004135 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004136 /* proper use of this character is caught by end_trigger:
4137 * if we see {, we call parse_group(..., end_trigger='}')
4138 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004139 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004140 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004141 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004142 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004143 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004144 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004145 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004146 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004147 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004148 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004149 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004150 return 0;
4151}
4152
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004153static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004154{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004155 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004156 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004157}
4158
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004159static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004160{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004161 G.ifs = getenv("IFS");
4162 if (G.ifs == NULL)
4163 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004164 /* Precompute a list of 'flow through' behavior so it can be treated
4165 * quickly up front. Computation is necessary because of IFS.
4166 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004167 * The charmap[] array only really needs two bits each,
4168 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004169 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004170 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004171#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004172 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004173#else
4174 set_in_charmap("\\$\"", CHAR_SPECIAL);
4175#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004176 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004177 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004178}
4179
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004180/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004181 * from builtin_source() and builtin_eval() */
4182static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004183{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004184 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004185 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004186 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004187
Eric Andersen25f27032001-04-26 23:22:31 +00004188 do {
4189 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004190 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004191#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004192 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004193#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004194 /* We will stop & execute after each ';' or '\n'.
4195 * Example: "sleep 9999; echo TEST" + ctrl-C:
4196 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004197 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004198 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004199#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004200 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004201 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004202 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004203#endif
4204 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004205 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004206 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004207 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004208 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4209 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004210 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004211 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004212#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004213 if (ctx.old_flag != 0) {
4214 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004215 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004216 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004217#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004218 /*temp.nonnull = 0; - o_free does it below */
4219 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004220 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004221 /* Discard all unprocessed line input, force prompt on */
4222 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004223#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004224 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004225#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004226 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004227 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004228 /* loop on syntax errors, return on EOF: */
4229 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004230 return 0;
4231}
4232
Denis Vlasenko170435c2007-05-23 13:01:10 +00004233static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004234{
4235 struct in_str input;
4236 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004237 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004238}
4239
Denis Vlasenko170435c2007-05-23 13:01:10 +00004240static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004241{
4242 int rcode;
4243 struct in_str input;
4244 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004245 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004246 return rcode;
4247}
4248
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004249#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004250/* Make sure we have a controlling tty. If we get started under a job
4251 * aware app (like bash for example), make sure we are now in charge so
4252 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004253static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004254{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004255 pid_t shell_pgrp;
4256
Denis Vlasenko87a86552008-07-29 19:43:10 +00004257 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004258 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004259
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004260 /* If we were ran as 'hush &',
4261 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004262 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004263 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004264 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004265 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004266 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004267
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004268 /* Ignore job-control and misc signals. */
4269 set_jobctrl_sighandler(SIG_IGN);
4270 set_misc_sighandler(SIG_IGN);
4271//huh? signal(SIGCHLD, SIG_IGN);
4272
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004273 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004274 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004275
4276 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004277 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004278 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004279 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004280}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004281#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004282
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004283
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004284int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004285int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004286{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004287 static const struct variable const_shell_ver = {
4288 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004289 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004290 .max_len = 1, /* 0 can provoke free(name) */
4291 .flg_export = 1,
4292 .flg_read_only = 1,
4293 };
4294
Eric Andersen25f27032001-04-26 23:22:31 +00004295 int opt;
4296 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004297 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004298 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004299
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004300 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004301
Denis Vlasenko87a86552008-07-29 19:43:10 +00004302 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004303
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004304 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004305 G.shell_ver = const_shell_ver; /* copying struct here */
4306 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004307 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004308 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4309 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004310 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004311 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004312 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004313 if (e) while (*e) {
4314 char *value = strchr(*e, '=');
4315 if (value) { /* paranoia */
4316 cur_var->next = xzalloc(sizeof(*cur_var));
4317 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004318 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004319 cur_var->max_len = strlen(*e);
4320 cur_var->flg_export = 1;
4321 }
4322 e++;
4323 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004324 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004325 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004326
Denis Vlasenko38f63192007-01-22 09:03:07 +00004327#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004328 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004329#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004330 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004331 G.global_argc = argc;
4332 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004333 /* Initialize some more globals to non-zero values */
4334 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004335#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00004336 if (ENABLE_FEATURE_EDITING)
4337 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004338 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004339#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004340
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004341 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004342 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004343
4344 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004345 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004346 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004347 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004348 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004349 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004350 fclose(input);
4351 }
Eric Andersen25f27032001-04-26 23:22:31 +00004352 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004353 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004354
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004355 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4356 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00004357 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004358 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004359 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00004360 if (!argv[optind]) {
4361 /* -c 'script' (no params): prevent empty $0 */
4362 *--G.global_argv = argv[0];
4363 optind--;
4364 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004365 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004366 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004367 goto final_return;
4368 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004369 /* Well, we cannot just declare interactiveness,
4370 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004371 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004372 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004373 case 's':
4374 /* "-s" means "read from stdin", but this is how we always
4375 * operate, so simply do nothing here. */
4376 break;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004377 case 'n':
4378 case 'x':
4379 if (!builtin_set_mode('-', opt))
4380 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004381 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004382#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004383 fprintf(stderr, "Usage: sh [FILE]...\n"
4384 " or: sh -c command [args]...\n\n");
4385 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004386#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004387 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004388#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004389 }
4390 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004391#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004392 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004393 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004394 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004395 * no arguments remaining or the -s flag given
4396 * standard input is a terminal
4397 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004398 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004399 if (argv[optind] == NULL && input == stdin
4400 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4401 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004402 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4403 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4404 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004405 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004406 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4407 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004408 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004409 G.interactive_fd = dup(STDIN_FILENO);
4410 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004411 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004412 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004413 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004414 // TODO: track & disallow any attempts of user
4415 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004416 }
Eric Andersen25f27032001-04-26 23:22:31 +00004417 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004418 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4419 if (G.interactive_fd) {
4420 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004421 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004422 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004423 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004424 * (we reset die_sleep = 0 whereever we [v]fork) */
4425 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004426 if (setjmp(die_jmp)) {
4427 /* xfunc has failed! die die die */
4428 hush_exit(xfunc_error_retval);
4429 }
Eric Andersenada18ff2001-05-21 16:18:22 +00004430 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004431#elif ENABLE_HUSH_INTERACTIVE
4432/* no job control compiled, only prompt/line editing */
4433 if (argv[optind] == NULL && input == stdin
4434 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4435 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004436 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4437 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004438 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004439 G.interactive_fd = dup(STDIN_FILENO);
4440 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004441 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004442 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004443 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004444 if (G.interactive_fd) {
4445 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004446 set_misc_sighandler(SIG_IGN);
4447 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004448 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004449#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004450
Mike Frysingerb2705e12009-03-23 08:44:02 +00004451 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G.interactive_fd) {
4452 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4453 printf("Enter 'help' for a list of built-in commands.\n\n");
4454 }
4455
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004456 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004457 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004458 } else {
4459 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004460 G.global_argv = argv + optind;
4461 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004462 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004463 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004464 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004465 }
Eric Andersen25f27032001-04-26 23:22:31 +00004466
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004467 final_return:
4468
Denis Vlasenko38f63192007-01-22 09:03:07 +00004469#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004470 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004471 if (G.cwd != bb_msg_unknown)
4472 free((char*)G.cwd);
4473 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004474 while (cur_var) {
4475 struct variable *tmp = cur_var;
4476 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004477 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004478 cur_var = cur_var->next;
4479 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004480 }
Eric Andersen25f27032001-04-26 23:22:31 +00004481#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004482 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004483}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004484
4485
4486#if ENABLE_LASH
4487int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4488int lash_main(int argc, char **argv)
4489{
4490 //bb_error_msg("lash is deprecated, please use hush instead");
4491 return hush_main(argc, argv);
4492}
4493#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004494
4495
4496/*
4497 * Built-ins
4498 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004499static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004500{
4501 return 0;
4502}
4503
4504static int builtin_test(char **argv)
4505{
4506 int argc = 0;
4507 while (*argv) {
4508 argc++;
4509 argv++;
4510 }
4511 return test_main(argc, argv - argc);
4512}
4513
4514static int builtin_echo(char **argv)
4515{
4516 int argc = 0;
4517 while (*argv) {
4518 argc++;
4519 argv++;
4520 }
4521 return echo_main(argc, argv - argc);
4522}
4523
4524static int builtin_eval(char **argv)
4525{
4526 int rcode = EXIT_SUCCESS;
4527
4528 if (argv[1]) {
4529 char *str = expand_strvec_to_string(argv + 1);
4530 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4531 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004532 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004533 }
4534 return rcode;
4535}
4536
4537static int builtin_cd(char **argv)
4538{
4539 const char *newdir;
4540 if (argv[1] == NULL) {
4541 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4542 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4543 newdir = getenv("HOME") ? : "/";
4544 } else
4545 newdir = argv[1];
4546 if (chdir(newdir)) {
4547 printf("cd: %s: %s\n", newdir, strerror(errno));
4548 return EXIT_FAILURE;
4549 }
4550 set_cwd();
4551 return EXIT_SUCCESS;
4552}
4553
4554static int builtin_exec(char **argv)
4555{
4556 if (argv[1] == NULL)
4557 return EXIT_SUCCESS; /* bash does this */
4558 {
4559#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004560 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004561#endif
4562// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004563 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004564 /* never returns */
4565 }
4566}
4567
4568static int builtin_exit(char **argv)
4569{
4570// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4571 //puts("exit"); /* bash does it */
4572// TODO: warn if we have background jobs: "There are stopped jobs"
4573// On second consecutive 'exit', exit anyway.
4574 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004575 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004576 /* mimic bash: exit 123abc == exit 255 + error msg */
4577 xfunc_error_retval = 255;
4578 /* bash: exit -2 == exit 254, no error msg */
4579 hush_exit(xatoi(argv[1]) & 0xff);
4580}
4581
4582static int builtin_export(char **argv)
4583{
4584 const char *value;
4585 char *name = argv[1];
4586
4587 if (name == NULL) {
4588 // TODO:
4589 // ash emits: export VAR='VAL'
4590 // bash: declare -x VAR="VAL"
4591 // (both also escape as needed (quotes, $, etc))
4592 char **e = environ;
4593 if (e)
4594 while (*e)
4595 puts(*e++);
4596 return EXIT_SUCCESS;
4597 }
4598
4599 value = strchr(name, '=');
4600 if (!value) {
4601 /* They are exporting something without a =VALUE */
4602 struct variable *var;
4603
4604 var = get_local_var(name);
4605 if (var) {
4606 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004607 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004608 putenv(var->varstr);
4609 }
4610 /* bash does not return an error when trying to export
4611 * an undefined variable. Do likewise. */
4612 return EXIT_SUCCESS;
4613 }
4614
4615 set_local_var(xstrdup(name), 1);
4616 return EXIT_SUCCESS;
4617}
4618
4619#if ENABLE_HUSH_JOB
4620/* built-in 'fg' and 'bg' handler */
4621static int builtin_fg_bg(char **argv)
4622{
4623 int i, jobnum;
4624 struct pipe *pi;
4625
Denis Vlasenko87a86552008-07-29 19:43:10 +00004626 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004627 return EXIT_FAILURE;
4628 /* If they gave us no args, assume they want the last backgrounded task */
4629 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004630 for (pi = G.job_list; pi; pi = pi->next) {
4631 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004632 goto found;
4633 }
4634 }
4635 bb_error_msg("%s: no current job", argv[0]);
4636 return EXIT_FAILURE;
4637 }
4638 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4639 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4640 return EXIT_FAILURE;
4641 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004642 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004643 if (pi->jobid == jobnum) {
4644 goto found;
4645 }
4646 }
4647 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4648 return EXIT_FAILURE;
4649 found:
4650 // TODO: bash prints a string representation
4651 // of job being foregrounded (like "sleep 1 | cat")
4652 if (*argv[0] == 'f') {
4653 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004654 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004655 }
4656
4657 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004658 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4659 for (i = 0; i < pi->num_cmds; i++) {
4660 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4661 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004662 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004663 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004664
4665 i = kill(- pi->pgrp, SIGCONT);
4666 if (i < 0) {
4667 if (errno == ESRCH) {
4668 delete_finished_bg_job(pi);
4669 return EXIT_SUCCESS;
4670 } else {
4671 bb_perror_msg("kill (SIGCONT)");
4672 }
4673 }
4674
4675 if (*argv[0] == 'f') {
4676 remove_bg_job(pi);
4677 return checkjobs_and_fg_shell(pi);
4678 }
4679 return EXIT_SUCCESS;
4680}
4681#endif
4682
4683#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004684static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004685{
4686 const struct built_in_command *x;
4687
4688 printf("\nBuilt-in commands:\n");
4689 printf("-------------------\n");
4690 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4691 printf("%s\t%s\n", x->cmd, x->descr);
4692 }
4693 printf("\n\n");
4694 return EXIT_SUCCESS;
4695}
4696#endif
4697
4698#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004699static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004700{
4701 struct pipe *job;
4702 const char *status_string;
4703
Denis Vlasenko87a86552008-07-29 19:43:10 +00004704 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004705 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004706 status_string = "Stopped";
4707 else
4708 status_string = "Running";
4709
4710 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4711 }
4712 return EXIT_SUCCESS;
4713}
4714#endif
4715
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004716static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004717{
4718 puts(set_cwd());
4719 return EXIT_SUCCESS;
4720}
4721
4722static int builtin_read(char **argv)
4723{
4724 char *string;
4725 const char *name = argv[1] ? argv[1] : "REPLY";
4726
4727 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4728 return set_local_var(string, 0);
4729}
4730
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004731/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4732 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004733 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004734 * set [-abCefhmnuvx] [-o option] [argument...]
4735 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004736 * set -- [argument...]
4737 * set -o
4738 * set +o
4739 * Implementations shall support the options in both their hyphen and
4740 * plus-sign forms. These options can also be specified as options to sh.
4741 * Examples:
4742 * Write out all variables and their values: set
4743 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4744 * Turn on the -x and -v options: set -xv
4745 * Unset all positional parameters: set --
4746 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4747 * Set the positional parameters to the expansion of x, even if x expands
4748 * with a leading '-' or '+': set -- $x
4749 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004750 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004751 */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004752static int builtin_set_mode(const char cstate, const char mode)
4753{
4754 int state = (cstate == '-' ? 1 : 0);
4755 switch (mode) {
4756 case 'n': G.fake_mode = state; break;
4757 case 'x': /*G.debug_mode = state;*/ break;
4758 default: return EXIT_FAILURE;
4759 }
4760 return EXIT_SUCCESS;
4761}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004762static int builtin_set(char **argv)
4763{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004764 int n;
4765 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004766 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004767
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004768 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004769 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004770 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004771 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004772 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004773 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004774
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004775 do {
4776 if (!strcmp(arg, "--")) {
4777 ++argv;
4778 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004779 }
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004780
4781 if (arg[0] == '+' || arg[0] == '-') {
4782 for (n = 1; arg[n]; ++n)
4783 if (builtin_set_mode(arg[0], arg[n]))
4784 goto error;
4785 continue;
4786 }
4787
4788 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004789 } while ((arg = *++argv) != NULL);
4790 /* Now argv[0] is 1st argument */
4791
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004792 /* Only reset global_argv if we didn't process anything */
4793 if (arg == NULL)
4794 return EXIT_SUCCESS;
4795 set_argv:
4796
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004797 /* NB: G.global_argv[0] ($0) is never freed/changed */
4798 g_argv = G.global_argv;
4799 if (G.global_args_malloced) {
4800 pp = g_argv;
4801 while (*++pp)
4802 free(*pp);
4803 g_argv[1] = NULL;
4804 } else {
4805 G.global_args_malloced = 1;
4806 pp = xzalloc(sizeof(pp[0]) * 2);
4807 pp[0] = g_argv[0]; /* retain $0 */
4808 g_argv = pp;
4809 }
4810 /* This realloc's G.global_argv */
4811 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4812
4813 n = 1;
4814 while (*++pp)
4815 n++;
4816 G.global_argc = n;
4817
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004818 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004819
4820 /* Nothing known, so abort */
4821 error:
4822 bb_error_msg("set: %s: invalid option", arg);
4823 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004824}
4825
4826static int builtin_shift(char **argv)
4827{
4828 int n = 1;
4829 if (argv[1]) {
4830 n = atoi(argv[1]);
4831 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004832 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004833 if (G.global_args_malloced) {
4834 int m = 1;
4835 while (m <= n)
4836 free(G.global_argv[m++]);
4837 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004838 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004839 memmove(&G.global_argv[1], &G.global_argv[n+1],
4840 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004841 return EXIT_SUCCESS;
4842 }
4843 return EXIT_FAILURE;
4844}
4845
4846static int builtin_source(char **argv)
4847{
4848 FILE *input;
4849 int status;
4850
4851 if (argv[1] == NULL)
4852 return EXIT_FAILURE;
4853
4854 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004855 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004856 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004857 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004858 return EXIT_FAILURE;
4859 }
4860 close_on_exec_on(fileno(input));
4861
4862 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004863 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004864 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00004865 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004866 status = parse_and_run_file(input);
4867 fclose(input);
4868 return status;
4869}
4870
4871static int builtin_umask(char **argv)
4872{
4873 mode_t new_umask;
4874 const char *arg = argv[1];
4875 char *end;
4876 if (arg) {
4877 new_umask = strtoul(arg, &end, 8);
4878 if (*end != '\0' || end == arg) {
4879 return EXIT_FAILURE;
4880 }
4881 } else {
4882 new_umask = umask(0);
4883 printf("%.3o\n", (unsigned) new_umask);
4884 }
4885 umask(new_umask);
4886 return EXIT_SUCCESS;
4887}
4888
4889static int builtin_unset(char **argv)
4890{
4891 /* bash always returns true */
4892 unset_local_var(argv[1]);
4893 return EXIT_SUCCESS;
4894}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004895
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004896#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004897static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004898{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004899 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004900 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004901 return EXIT_SUCCESS; /* bash compat */
4902 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004903 G.flag_break_continue++; /* BC_BREAK = 1 */
4904 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004905 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004906 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4907 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004908 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004909 G.flag_break_continue = BC_BREAK;
4910 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004911 }
4912 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004913 if (G.depth_of_loop < G.depth_break_continue)
4914 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004915 return EXIT_SUCCESS;
4916}
4917
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004918static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004919{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004920 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4921 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004922}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004923#endif