blob: bcccfb0bb969ddc61171bebe3339b3877407e3d6 [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;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000463//// smallint ctrl_z_flag;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000464#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;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000469 /* These four 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];
Denis Vlasenkod5762932009-03-31 11:22:57 +0000492 /* Signal and trap handling */
493 char **traps; /* char *traps[NSIG] */
494 /* which signals have non-DFL handler (even with no traps set)? */
495 unsigned non_DFL_mask;
496 /* which signals are known to be IGNed on entry to shell? */
497 unsigned IGN_mask;
498 sigset_t blocked_set;
499 sigset_t inherited_set;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000500};
501
502#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000503/* Not #defining name to G.name - this quickly gets unwieldy
504 * (too many defines). Also, I actually prefer to see when a variable
505 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000506#define INIT_G() do { \
507 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
508} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000509
510
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000511/* Function prototypes for builtins */
512static int builtin_cd(char **argv);
513static int builtin_echo(char **argv);
514static int builtin_eval(char **argv);
515static int builtin_exec(char **argv);
516static int builtin_exit(char **argv);
517static int builtin_export(char **argv);
518#if ENABLE_HUSH_JOB
519static int builtin_fg_bg(char **argv);
520static int builtin_jobs(char **argv);
521#endif
522#if ENABLE_HUSH_HELP
523static int builtin_help(char **argv);
524#endif
525static int builtin_pwd(char **argv);
526static int builtin_read(char **argv);
527static int builtin_test(char **argv);
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000528static int builtin_trap(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000529static int builtin_true(char **argv);
530static int builtin_set(char **argv);
531static int builtin_shift(char **argv);
532static int builtin_source(char **argv);
533static int builtin_umask(char **argv);
534static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000535static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000536#if ENABLE_HUSH_LOOPS
537static int builtin_break(char **argv);
538static int builtin_continue(char **argv);
539#endif
540//static int builtin_not_written(char **argv);
541
542/* Table of built-in functions. They can be forked or not, depending on
543 * context: within pipes, they fork. As simple commands, they do not.
544 * When used in non-forking context, they can change global variables
545 * in the parent shell process. If forked, of course they cannot.
546 * For example, 'unset foo | whatever' will parse and run, but foo will
547 * still be set at the end. */
548struct built_in_command {
549 const char *cmd;
550 int (*function)(char **argv);
551#if ENABLE_HUSH_HELP
552 const char *descr;
553#define BLTIN(cmd, func, help) { cmd, func, help }
554#else
555#define BLTIN(cmd, func, help) { cmd, func }
556#endif
557};
558
559/* For now, echo and test are unconditionally enabled.
560 * Maybe make it configurable? */
561static const struct built_in_command bltins[] = {
562 BLTIN("." , builtin_source, "Run commands in a file"),
563 BLTIN(":" , builtin_true, "No-op"),
564 BLTIN("[" , builtin_test, "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000565#if ENABLE_HUSH_JOB
566 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
567#endif
568#if ENABLE_HUSH_LOOPS
569 BLTIN("break" , builtin_break, "Exit from a loop"),
570#endif
571 BLTIN("cd" , builtin_cd, "Change directory"),
572#if ENABLE_HUSH_LOOPS
573 BLTIN("continue", builtin_continue, "Start new loop iteration"),
574#endif
575 BLTIN("echo" , builtin_echo, "Write to stdout"),
576 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
577 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
578 BLTIN("exit" , builtin_exit, "Exit"),
579 BLTIN("export", builtin_export, "Set environment variable"),
580#if ENABLE_HUSH_JOB
581 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
582 BLTIN("jobs" , builtin_jobs, "List active jobs"),
583#endif
584 BLTIN("pwd" , builtin_pwd, "Print current directory"),
585 BLTIN("read" , builtin_read, "Input environment variable"),
586// BLTIN("return", builtin_not_written, "Return from a function"),
587 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
588 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000589 BLTIN("test" , builtin_test, "Test condition"),
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000590 BLTIN("trap" , builtin_trap, "Trap signals"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000591// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
592 BLTIN("umask" , builtin_umask, "Set file creation mask"),
593 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Mike Frysinger56bdea12009-03-28 20:01:58 +0000594 BLTIN("wait" , builtin_wait, "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000595#if ENABLE_HUSH_HELP
596 BLTIN("help" , builtin_help, "List shell built-in commands"),
597#endif
598};
599
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000600
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000601/* Normal */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000602static void maybe_die(const char *notice, const char *msg)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000603{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000604 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000605 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000606 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000607 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
608#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +0000609 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000610#endif
Mike Frysinger6379bb42009-03-28 18:55:03 +0000611 fp(msg ? "%s: %s" : notice, notice, msg);
612}
Mike Frysinger5a828452009-03-28 19:09:04 +0000613#if 1
614#define syntax(msg) maybe_die("syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000615#else
Mike Frysinger5a828452009-03-28 19:09:04 +0000616/* Debug -- trick gcc to expand __LINE__ and convert to string */
617#define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
618#define _syntax(msg, line) __syntax(msg, line)
619#define syntax(msg) _syntax(msg, __LINE__)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000620#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000621
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000622static int glob_needed(const char *s)
623{
624 while (*s) {
625 if (*s == '\\')
626 s++;
627 if (*s == '*' || *s == '[' || *s == '?')
628 return 1;
629 s++;
630 }
631 return 0;
632}
633
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000634static int is_assignment(const char *s)
635{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000636 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000637 return 0;
638 s++;
639 while (isalnum(*s) || *s == '_')
640 s++;
641 return *s == '=';
642}
643
Denis Vlasenko55789c62008-06-18 16:30:42 +0000644/* Replace each \x with x in place, return ptr past NUL. */
645static char *unbackslash(char *src)
646{
647 char *dst = src;
648 while (1) {
649 if (*src == '\\')
650 src++;
651 if ((*dst++ = *src++) == '\0')
652 break;
653 }
654 return dst;
655}
656
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000657static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000658{
659 int i;
660 unsigned count1;
661 unsigned count2;
662 char **v;
663
664 v = strings;
665 count1 = 0;
666 if (v) {
667 while (*v) {
668 count1++;
669 v++;
670 }
671 }
672 count2 = 0;
673 v = add;
674 while (*v) {
675 count2++;
676 v++;
677 }
678 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
679 v[count1 + count2] = NULL;
680 i = count2;
681 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000682 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000683 return v;
684}
685
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000686static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000687{
688 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000689 v[0] = add;
690 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000691 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000692}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000693
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000694static void putenv_all(char **strings)
695{
696 if (!strings)
697 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000698 while (*strings) {
699 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000700 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000701 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000702}
703
704static char **putenv_all_and_save_old(char **strings)
705{
706 char **old = NULL;
707 char **s = strings;
708
709 if (!strings)
710 return old;
711 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000712 char *v, *eq;
713
714 eq = strchr(*strings, '=');
715 if (eq) {
716 *eq = '\0';
717 v = getenv(*strings);
718 *eq = '=';
719 if (v) {
720 /* v points to VAL in VAR=VAL, go back to VAR */
721 v -= (eq - *strings) + 1;
722 old = add_string_to_strings(old, v);
723 }
724 }
725 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000726 }
727 putenv_all(s);
728 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000729}
730
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000731static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000732{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000733 char **v;
734
735 if (!strings)
736 return;
737
738 v = strings;
739 while (*v) {
740 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000741 debug_printf_env("unsetenv '%s'\n", *v);
742 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000743 }
744 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000745 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000746 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000747}
748
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000749static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000750{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000751 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000752}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000753
754
Denis Vlasenkod5762932009-03-31 11:22:57 +0000755/* Basic theory of signal handling in shell
756 * ========================================
757 * This does not describe what hush does, rahter, it is current understanding
758 * what it _should_ do.
759 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
760 *
761 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
762 * is finished or backgrounded. It is the same in interactive and
763 * non-interactive shells, and is the same regardless of whether
764 * a user trap handler is installed or a default one is in effect.
765 * ^C or ^Z from keyboard seem to execute "at once" because it usually
766 * backgrounds (i.e. stops) or kills all members of currently running
767 * pipe.
768 *
769 * Wait builtin in interruptible by signals for which user trap is set
770 * or by SIGINT in interactive shell.
771 *
772 * Trap handlers will execute even within trap handlers. (right?)
773 *
774 * User trap handlers are forgotten when subshell is entered.
775 *
776 * If job control is off, backgrounded commands ("cmd &")
777 * have SIGINT, SIGQUIT set to SIG_IGN.
778 *
779 * Commands run in command substitution ("`cmd`")
780 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
781 *
782 * Ordinary commands have IGN/DFL set as inherited by the shell
783 * from its parent.
784 *
785 * Default handlers which differ from DFL action
786 * (note: subshell is not an interactive shell):
787 *
788 * SIGQUIT: ignore
789 * SIGTERM (interactive): ignore
790 * SUGHUP (interactive): send SIGCONT to stopped jobs,
791 * send SIGHUP to all jobs and exit
792 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
793 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
794 * that all pipe members are stopped) (right?)
795 * SIGINT (interactive): wait for last pipe, ignore the rest
796 * of the command line, show prompt. (check/expand this)
797 * Example 1: this waits 5 sec, but does not execute ls:
798 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
799 * Example 2: this does not wait and does not execute ls:
800 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
801 *
802 * (What happens to signals which are IGN on shell start?)
803 * (What happens with signal mask on shell start?)
804 *
805 * Implementation in hush
806 * ======================
807 * We use in-kernel pending signal mask to determine which signals were sent.
808 * We block all signals which we don't want to take action immediately,
809 * i.e. we block all signals which need to have special handling as described
810 * above, and all signals which have traps set.
811 * After each pipe execution, we extract any pending signals via sigtimedwait()
812 * and act on them.
813 *
814 * unsigned non_DFL_mask: a mask of such "special" signals
815 * sigset_t blocked_set: current blocked signal set
816 *
817 * "trap - SIGxxx": clear bit in blocked_set unless it is also in non_DFL
818 * "trap 'cmd' SIGxxx": set bit in blocked_set (even if 'cmd' is '')
819 * after [v]fork, if we plan to be a shell:
820 * nothing for {} subshell (say, "true | { true; true; } | true")
821 * unset all traps if () shell. [TODO]
822 * after [v]fork, if we plan to exec:
823 * POSIX says pending signal mask is cleared in child - no need to clear it.
824 * restore blocked signal set to one inherited by shell just prior to exec.
825 *
826 * Note: as a result, we do not use signal handlers much. The only use
827 * is to restore terminal pgrp on exit.
828 *
829 * TODO: check/fix wait builtin to be interruptible.
830 */
831
832/* called once at shell init */
833static void init_signal_mask(void)
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000834{
Denis Vlasenkod5762932009-03-31 11:22:57 +0000835 unsigned sig;
836 unsigned mask = (1 << SIGQUIT);
837#if ENABLE_HUSH_INTERACTIVE
838 if (G.interactive_fd) {
839 mask = 0
840 | (1 << SIGQUIT)
841 | (1 << SIGTERM)
842 | (1 << SIGHUP)
843#if ENABLE_HUSH_JOB
844 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
845#endif
846 | (1 << SIGINT)
847 ;
848 }
849#endif
850 G.non_DFL_mask = mask;
851
852 /*sigemptyset(&G.blocked_set); - already is */
853 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
854 sig = 0;
855 while (mask) {
856 if (mask & 1)
857 sigaddset(&G.blocked_set, sig);
858 mask >>= 1;
859 sig++;
860 }
861 sigprocmask(SIG_SETMASK, &G.blocked_set, &G.inherited_set);
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000862}
Denis Vlasenkod5762932009-03-31 11:22:57 +0000863static void check_and_run_traps(void)
864{
865 static const struct timespec zero_ts = { 0, 0 };
866 smalluint save_rcode;
867 int sig;
868
869 while (1) {
870 sig = sigtimedwait(&G.blocked_set, NULL, &zero_ts);
871 if (sig <= 0)
872 break;
873
874 if (G.traps && G.traps[sig]) {
875 if (G.traps[sig][0]) {
876 /* We have user-defined handler */
877 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
878 save_rcode = G.last_return_code;
879 builtin_eval(argv);
880 free(argv[1]);
881 G.last_return_code = save_rcode;
882 } /* else: "" trap, ignoring signal */
883 continue;
884 }
885 /* not a trap: special action */
886#if 0 //TODO
887 switch (sig) {
888 case SIGHUP: ...
889 break;
890 case SIGINT: ...
891 break;
892 default: /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
893 }
894#endif
895 }
896}
897
898/* The stuff below needs to be migrated to "Special action" above */
899
900/////* Signals are grouped, we handle them in batches */
901////static void set_misc_sighandler(void (*handler)(int))
902////{
903//// bb_signals(0
904//// + (1 << SIGINT)
905//// + (1 << SIGQUIT)
906//// + (1 << SIGTERM)
907//// , handler);
908////}
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000909
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000910#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000911
Denis Vlasenkod5762932009-03-31 11:22:57 +0000912/* helper */
913static unsigned maybe_set_sighandler(int sig, void (*handler)(int))
914{
915 /* non_DFL_mask'ed signals are, well, masked,
916 * no need to set handler for them.
917 * IGN_mask'ed signals were found to be IGN on entry,
918 * do not change that -> no need to set handler for them either
919 */
920 unsigned ign = ((G.IGN_mask|G.non_DFL_mask) >> sig) & 1;
921 if (!ign) {
922 handler = signal(sig, handler);
923 ign = (handler == SIG_IGN);
924 if (ign) /* restore back to IGN! */
925 signal(sig, handler);
926 }
927 return ign << sig; /* pass back knowledge about SIG_IGN */
928}
929/* Used only to set handler to restore pgrp on exit, and to reset it to DFL */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000930static void set_fatal_sighandler(void (*handler)(int))
931{
Denis Vlasenkod5762932009-03-31 11:22:57 +0000932 unsigned mask = 0;
933
934 if (HUSH_DEBUG) {
935 mask |= maybe_set_sighandler(SIGILL , handler);
936 mask |= maybe_set_sighandler(SIGFPE , handler);
937 mask |= maybe_set_sighandler(SIGBUS , handler);
938 mask |= maybe_set_sighandler(SIGSEGV, handler);
939 mask |= maybe_set_sighandler(SIGTRAP, handler);
940 } /* else: hush is perfect. what SEGV? */
941
942 mask |= maybe_set_sighandler(SIGABRT, handler);
943
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000944 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000945 mask |= maybe_set_sighandler(SIGPIPE, handler);
946 mask |= maybe_set_sighandler(SIGALRM, handler);
947 mask |= maybe_set_sighandler(SIGHUP , handler);
948
949 /* if we aren't interactive... but in this case
950 * we never want to restore pgrp on exit, and this fn is not called */
951 /*mask |= maybe_set_sighandler(SIGTERM, handler); */
952 /*mask |= maybe_set_sighandler(SIGINT , handler); */
953
954 G.IGN_mask = mask;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000955}
Denis Vlasenkod5762932009-03-31 11:22:57 +0000956/* Used only to suppress ^Z in `cmd` */
957static void IGN_jobctrl_signals(void)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000958{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000959 bb_signals(0
960 + (1 << SIGTSTP)
961 + (1 << SIGTTIN)
962 + (1 << SIGTTOU)
Denis Vlasenkod5762932009-03-31 11:22:57 +0000963 , SIG_IGN);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000964}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000965/* SIGCHLD is special and handled separately */
966
Denis Vlasenkod5762932009-03-31 11:22:57 +0000967////static void set_every_sighandler(void (*handler)(int))
968////{
969//// set_fatal_sighandler(handler);
970//// set_jobctrl_sighandler(handler);
971//// set_misc_sighandler(handler);
972//// signal(SIGCHLD, handler);
973////}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000974
Denis Vlasenkod5762932009-03-31 11:22:57 +0000975////static void handler_ctrl_c(int sig UNUSED_PARAM)
976////{
977//// debug_printf_jobs("got sig %d\n", sig);
978////// as usual we can have all kinds of nasty problems with leaked malloc data here
979//// siglongjmp(G.toplevel_jb, 1);
980////}
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000981
Denis Vlasenkod5762932009-03-31 11:22:57 +0000982////static void handler_ctrl_z(int sig UNUSED_PARAM)
983////{
984//// pid_t pid;
985////
986//// debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
987////
988//// if (!BB_MMU) {
989//// fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
990//// return;
991//// }
992////
993//// pid = fork();
994//// if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
995//// return;
996//// G.ctrl_z_flag = 1;
997//// if (!pid) { /* child */
998//// if (ENABLE_HUSH_JOB)
999//// die_sleep = 0; /* let nofork's xfuncs die */
1000//// bb_setpgrp();
1001//// debug_printf_jobs("set pgrp for child %d ok\n", getpid());
1002//////// set_every_sighandler(SIG_DFL);
1003//// raise(SIGTSTP); /* resend TSTP so that child will be stopped */
1004//// debug_printf_jobs("returning in child\n");
1005//// /* return to nofork, it will eventually exit now,
1006//// * not return back to shell */
1007//// return;
1008//// }
1009//// /* parent */
1010//// /* finish filling up pipe info */
1011//// G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
1012//// G.toplevel_list->cmds[0].pid = pid;
1013//// /* parent needs to longjmp out of running nofork.
1014//// * we will "return" exitcode 0, with child put in background */
1015////// as usual we can have all kinds of nasty problems with leaked malloc data here
1016//// debug_printf_jobs("siglongjmp in parent\n");
1017//// siglongjmp(G.toplevel_jb, 1);
1018////}
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00001019
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001020/* Restores tty foreground process group, and exits.
1021 * May be called as signal handler for fatal signal
1022 * (will faithfully resend signal to itself, producing correct exit state)
1023 * or called directly with -EXITCODE.
1024 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001025static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001026static void sigexit(int sig)
1027{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001028 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001029 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001030
Denis Vlasenko87a86552008-07-29 19:43:10 +00001031#if ENABLE_HUSH_INTERACTIVE
1032 if (G.interactive_fd)
1033 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
1034#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001035
1036 /* Not a signal, just exit */
1037 if (sig <= 0)
1038 _exit(- sig);
1039
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001040 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001041}
1042
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001043#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001044
Denis Vlasenkod5762932009-03-31 11:22:57 +00001045#define set_fatal_sighandler(handler) ((void)0)
1046#define IGN_jobctrl_signals(handler) ((void)0)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001047
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001048#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001049
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001050/* Restores tty foreground process group, and exits. */
1051static void hush_exit(int exitcode) NORETURN;
1052static void hush_exit(int exitcode)
1053{
Denis Vlasenkod5762932009-03-31 11:22:57 +00001054 if (G.traps && G.traps[0] && G.traps[0][0]) {
1055 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
1056 builtin_eval(argv);
1057 free(argv[1]);
1058 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001059
1060 if (ENABLE_HUSH_JOB) {
1061 fflush(NULL); /* flush all streams */
1062 sigexit(- (exitcode & 0xff));
1063 } else
1064 exit(exitcode);
1065}
1066
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001067
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001068static const char *set_cwd(void)
1069{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001070 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1071 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001072 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001073 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001074 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1075 if (!G.cwd)
1076 G.cwd = bb_msg_unknown;
1077 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001078}
1079
Denis Vlasenko83506862007-11-23 13:11:42 +00001080
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001081/* Get/check local shell variables */
1082static struct variable *get_local_var(const char *name)
1083{
1084 struct variable *cur;
1085 int len;
1086
1087 if (!name)
1088 return NULL;
1089 len = strlen(name);
1090 for (cur = G.top_var; cur; cur = cur->next) {
1091 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1092 return cur;
1093 }
1094 return NULL;
1095}
1096
1097/* Basically useful version until someone wants to get fancier,
1098 * see the bash man page under "Parameter Expansion" */
1099static const char *lookup_param(const char *src)
1100{
1101 struct variable *var = get_local_var(src);
1102 if (var)
1103 return strchr(var->varstr, '=') + 1;
1104 return NULL;
1105}
1106
1107/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001108 * We take ownership of it.
1109 * flg_export is used by:
1110 * 0: do not export
1111 * 1: export
1112 * -1: if NAME is set, leave export status alone
1113 * if NAME is not set, do not export
1114 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001115static int set_local_var(char *str, int flg_export)
1116{
1117 struct variable *cur;
1118 char *value;
1119 int name_len;
1120
1121 value = strchr(str, '=');
1122 if (!value) { /* not expected to ever happen? */
1123 free(str);
1124 return -1;
1125 }
1126
1127 name_len = value - str + 1; /* including '=' */
1128 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1129 while (1) {
1130 if (strncmp(cur->varstr, str, name_len) != 0) {
1131 if (!cur->next) {
1132 /* Bail out. Note that now cur points
1133 * to last var in linked list */
1134 break;
1135 }
1136 cur = cur->next;
1137 continue;
1138 }
1139 /* We found an existing var with this name */
1140 *value = '\0';
1141 if (cur->flg_read_only) {
1142 bb_error_msg("%s: readonly variable", str);
1143 free(str);
1144 return -1;
1145 }
1146 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1147 unsetenv(str); /* just in case */
1148 *value = '=';
1149 if (strcmp(cur->varstr, str) == 0) {
1150 free_and_exp:
1151 free(str);
1152 goto exp;
1153 }
1154 if (cur->max_len >= strlen(str)) {
1155 /* This one is from startup env, reuse space */
1156 strcpy(cur->varstr, str);
1157 goto free_and_exp;
1158 }
1159 /* max_len == 0 signifies "malloced" var, which we can
1160 * (and has to) free */
1161 if (!cur->max_len)
1162 free(cur->varstr);
1163 cur->max_len = 0;
1164 goto set_str_and_exp;
1165 }
1166
1167 /* Not found - create next variable struct */
1168 cur->next = xzalloc(sizeof(*cur));
1169 cur = cur->next;
1170
1171 set_str_and_exp:
1172 cur->varstr = str;
1173 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001174 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001175 cur->flg_export = 1;
1176 if (cur->flg_export) {
1177 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1178 return putenv(cur->varstr);
1179 }
1180 return 0;
1181}
1182
Mike Frysingerd690f682009-03-30 06:50:54 +00001183static int unset_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001184{
1185 struct variable *cur;
1186 struct variable *prev = prev; /* for gcc */
1187 int name_len;
1188
1189 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001190 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001191 name_len = strlen(name);
1192 cur = G.top_var;
1193 while (cur) {
1194 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1195 if (cur->flg_read_only) {
1196 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001197 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001198 }
1199 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1200 * is ro, and we cannot reach this code on the 1st pass */
1201 prev->next = cur->next;
1202 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1203 bb_unsetenv(cur->varstr);
1204 if (!cur->max_len)
1205 free(cur->varstr);
1206 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001207 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001208 }
1209 prev = cur;
1210 cur = cur->next;
1211 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001212 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001213}
1214
1215
1216/*
1217 * in_str support
1218 */
1219static int static_get(struct in_str *i)
1220{
1221 int ch = *i->p++;
1222 if (ch == '\0') return EOF;
1223 return ch;
1224}
1225
1226static int static_peek(struct in_str *i)
1227{
1228 return *i->p;
1229}
1230
1231#if ENABLE_HUSH_INTERACTIVE
1232
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001233static void cmdedit_set_initial_prompt(void)
1234{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001235 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1236 G.PS1 = getenv("PS1");
1237 if (G.PS1 == NULL)
1238 G.PS1 = "\\w \\$ ";
1239 } else
1240 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001241}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001242
1243static const char* setup_prompt_string(int promptmode)
1244{
1245 const char *prompt_str;
1246 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001247 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1248 /* Set up the prompt */
1249 if (promptmode == 0) { /* PS1 */
1250 free((char*)G.PS1);
1251 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1252 prompt_str = G.PS1;
1253 } else
1254 prompt_str = G.PS2;
1255 } else
1256 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001257 debug_printf("result '%s'\n", prompt_str);
1258 return prompt_str;
1259}
1260
1261static void get_user_input(struct in_str *i)
1262{
1263 int r;
1264 const char *prompt_str;
1265
1266 prompt_str = setup_prompt_string(i->promptmode);
1267#if ENABLE_FEATURE_EDITING
1268 /* Enable command line editing only while a command line
1269 * is actually being read */
1270 do {
1271 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1272 } while (r == 0); /* repeat if Ctrl-C */
1273 i->eof_flag = (r < 0);
1274 if (i->eof_flag) { /* EOF/error detected */
1275 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1276 G.user_input_buf[1] = '\0';
1277 }
1278#else
1279 fputs(prompt_str, stdout);
1280 fflush(stdout);
1281 G.user_input_buf[0] = r = fgetc(i->file);
1282 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1283 i->eof_flag = (r == EOF);
1284#endif
1285 i->p = G.user_input_buf;
1286}
1287
1288#endif /* INTERACTIVE */
1289
1290/* This is the magic location that prints prompts
1291 * and gets data back from the user */
1292static int file_get(struct in_str *i)
1293{
1294 int ch;
1295
1296 /* If there is data waiting, eat it up */
1297 if (i->p && *i->p) {
1298#if ENABLE_HUSH_INTERACTIVE
1299 take_cached:
1300#endif
1301 ch = *i->p++;
1302 if (i->eof_flag && !*i->p)
1303 ch = EOF;
1304 } else {
1305 /* need to double check i->file because we might be doing something
1306 * more complicated by now, like sourcing or substituting. */
1307#if ENABLE_HUSH_INTERACTIVE
1308 if (G.interactive_fd && i->promptme && i->file == stdin) {
1309 do {
1310 get_user_input(i);
1311 } while (!*i->p); /* need non-empty line */
1312 i->promptmode = 1; /* PS2 */
1313 i->promptme = 0;
1314 goto take_cached;
1315 }
1316#endif
1317 ch = fgetc(i->file);
1318 }
1319 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1320#if ENABLE_HUSH_INTERACTIVE
1321 if (ch == '\n')
1322 i->promptme = 1;
1323#endif
1324 return ch;
1325}
1326
1327/* All the callers guarantee this routine will never be
1328 * used right after a newline, so prompting is not needed.
1329 */
1330static int file_peek(struct in_str *i)
1331{
1332 int ch;
1333 if (i->p && *i->p) {
1334 if (i->eof_flag && !i->p[1])
1335 return EOF;
1336 return *i->p;
1337 }
1338 ch = fgetc(i->file);
1339 i->eof_flag = (ch == EOF);
1340 i->peek_buf[0] = ch;
1341 i->peek_buf[1] = '\0';
1342 i->p = i->peek_buf;
1343 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1344 return ch;
1345}
1346
1347static void setup_file_in_str(struct in_str *i, FILE *f)
1348{
1349 i->peek = file_peek;
1350 i->get = file_get;
1351#if ENABLE_HUSH_INTERACTIVE
1352 i->promptme = 1;
1353 i->promptmode = 0; /* PS1 */
1354#endif
1355 i->file = f;
1356 i->p = NULL;
1357}
1358
1359static void setup_string_in_str(struct in_str *i, const char *s)
1360{
1361 i->peek = static_peek;
1362 i->get = static_get;
1363#if ENABLE_HUSH_INTERACTIVE
1364 i->promptme = 1;
1365 i->promptmode = 0; /* PS1 */
1366#endif
1367 i->p = s;
1368 i->eof_flag = 0;
1369}
1370
1371
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001372/*
1373 * o_string support
1374 */
1375#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001376
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001377static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001378{
1379 o->length = 0;
1380 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001381 if (o->data)
1382 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001383}
1384
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001385static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001386{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001387 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001388 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001389}
1390
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001391static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001392{
1393 if (o->length + len > o->maxlen) {
1394 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1395 o->data = xrealloc(o->data, 1 + o->maxlen);
1396 }
1397}
1398
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001399static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001400{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001401 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1402 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001403 o->data[o->length] = ch;
1404 o->length++;
1405 o->data[o->length] = '\0';
1406}
1407
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001408static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001409{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001410 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001411 memcpy(&o->data[o->length], str, len);
1412 o->length += len;
1413 o->data[o->length] = '\0';
1414}
1415
Denis Vlasenko55789c62008-06-18 16:30:42 +00001416static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1417{
1418 while (len) {
1419 o_addchr(o, *str);
1420 if (*str++ == '\\'
1421 && (*str != '*' && *str != '?' && *str != '[')
1422 ) {
1423 o_addchr(o, '\\');
1424 }
1425 len--;
1426 }
1427}
1428
Eric Andersen25f27032001-04-26 23:22:31 +00001429/* My analysis of quoting semantics tells me that state information
1430 * is associated with a destination, not a source.
1431 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001432static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001433{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001434 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001435 char *found = strchr("*?[\\", ch);
1436 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001437 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001438 o_grow_by(o, sz);
1439 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001440 o->data[o->length] = '\\';
1441 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001442 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001443 o->data[o->length] = ch;
1444 o->length++;
1445 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001446}
1447
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001448static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001449{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001450 int sz = 1;
1451 if (o->o_quote && strchr("*?[\\", ch)) {
1452 sz++;
1453 o->data[o->length] = '\\';
1454 o->length++;
1455 }
1456 o_grow_by(o, sz);
1457 o->data[o->length] = ch;
1458 o->length++;
1459 o->data[o->length] = '\0';
1460}
1461
1462static void o_addQstr(o_string *o, const char *str, int len)
1463{
1464 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001465 o_addstr(o, str, len);
1466 return;
1467 }
1468 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001469 char ch;
1470 int sz;
1471 int ordinary_cnt = strcspn(str, "*?[\\");
1472 if (ordinary_cnt > len) /* paranoia */
1473 ordinary_cnt = len;
1474 o_addstr(o, str, ordinary_cnt);
1475 if (ordinary_cnt == len)
1476 return;
1477 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001478 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001479
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001480 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001481 sz = 1;
1482 if (ch) { /* it is necessarily one of "*?[\\" */
1483 sz++;
1484 o->data[o->length] = '\\';
1485 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001486 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001487 o_grow_by(o, sz);
1488 o->data[o->length] = ch;
1489 o->length++;
1490 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001491 }
1492}
1493
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001494/* A special kind of o_string for $VAR and `cmd` expansion.
1495 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001496 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001497 * list[i] contains an INDEX (int!) into this string data.
1498 * It means that if list[] needs to grow, data needs to be moved higher up
1499 * but list[i]'s need not be modified.
1500 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001501 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001502 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1503 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001504#if DEBUG_EXPAND || DEBUG_GLOB
1505static void debug_print_list(const char *prefix, o_string *o, int n)
1506{
1507 char **list = (char**)o->data;
1508 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1509 int i = 0;
1510 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1511 prefix, list, n, string_start, o->length, o->maxlen);
1512 while (i < n) {
1513 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1514 o->data + (int)list[i] + string_start,
1515 o->data + (int)list[i] + string_start);
1516 i++;
1517 }
1518 if (n) {
1519 const char *p = o->data + (int)list[n - 1] + string_start;
Mike Frysingerd006edb2009-03-28 12:43:53 +00001520 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001521 }
1522}
1523#else
1524#define debug_print_list(prefix, o, n) ((void)0)
1525#endif
1526
1527/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1528 * in list[n] so that it points past last stored byte so far.
1529 * It returns n+1. */
1530static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001531{
1532 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001533 int string_start;
1534 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001535
1536 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001537 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1538 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001539 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001540 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001541 /* list[n] points to string_start, make space for 16 more pointers */
1542 o->maxlen += 0x10 * sizeof(list[0]);
1543 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001544 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001545 memmove(list + n + 0x10, list + n, string_len);
1546 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001547 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001548 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001549 } else {
1550 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001551 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1552 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001553 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001554 o->has_empty_slot = 0;
1555 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001556 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001557 return n + 1;
1558}
1559
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001560/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001561static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001562{
1563 char **list = (char**)o->data;
1564 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1565
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001566 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001567}
1568
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001569/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001570 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001571static int o_glob(o_string *o, int n)
1572{
1573 glob_t globdata;
1574 int gr;
1575 char *pattern;
1576
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001577 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001578 if (!o->data)
1579 return o_save_ptr_helper(o, n);
1580 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001581 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001582 if (!glob_needed(pattern)) {
1583 literal:
1584 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001585 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001586 return o_save_ptr_helper(o, n);
1587 }
1588
1589 memset(&globdata, 0, sizeof(globdata));
1590 gr = glob(pattern, 0, NULL, &globdata);
1591 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1592 if (gr == GLOB_NOSPACE)
1593 bb_error_msg_and_die("out of memory during glob");
1594 if (gr == GLOB_NOMATCH) {
1595 globfree(&globdata);
1596 goto literal;
1597 }
1598 if (gr != 0) { /* GLOB_ABORTED ? */
1599//TODO: testcase for bad glob pattern behavior
1600 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1601 }
1602 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1603 char **argv = globdata.gl_pathv;
1604 o->length = pattern - o->data; /* "forget" pattern */
1605 while (1) {
1606 o_addstr(o, *argv, strlen(*argv) + 1);
1607 n = o_save_ptr_helper(o, n);
1608 argv++;
1609 if (!*argv)
1610 break;
1611 }
1612 }
1613 globfree(&globdata);
1614 if (DEBUG_GLOB)
1615 debug_print_list("o_glob returning", o, n);
1616 return n;
1617}
1618
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001619/* If o->o_glob == 1, glob the string so far remembered.
1620 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001621static int o_save_ptr(o_string *o, int n)
1622{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001623 if (o->o_glob) { /* if globbing is requested */
1624 /* If o->has_empty_slot, list[n] was already globbed
1625 * (if it was requested back then when it was filled)
1626 * so don't do that again! */
1627 if (!o->has_empty_slot)
1628 return o_glob(o, n); /* o_save_ptr_helper is inside */
1629 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001630 return o_save_ptr_helper(o, n);
1631}
1632
1633/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001634static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001635{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001636 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001637 int string_start;
1638
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001639 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1640 if (DEBUG_EXPAND)
1641 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001642 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001643 list = (char**)o->data;
1644 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1645 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001646 while (n) {
1647 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001648 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001649 }
1650 return list;
1651}
1652
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001653
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001654/* expand_strvec_to_strvec() takes a list of strings, expands
1655 * all variable references within and returns a pointer to
1656 * a list of expanded strings, possibly with larger number
1657 * of strings. (Think VAR="a b"; echo $VAR).
1658 * This new list is allocated as a single malloc block.
1659 * NULL-terminated list of char* pointers is at the beginning of it,
1660 * followed by strings themself.
1661 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001662
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001663/* Store given string, finalizing the word and starting new one whenever
1664 * we encounter IFS char(s). This is used for expanding variable values.
1665 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1666static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001667{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001668 while (1) {
1669 int word_len = strcspn(str, G.ifs);
1670 if (word_len) {
1671 if (output->o_quote || !output->o_glob)
1672 o_addQstr(output, str, word_len);
1673 else /* protect backslashes against globbing up :) */
1674 o_addstr_duplicate_backslash(output, str, word_len);
1675 str += word_len;
1676 }
1677 if (!*str) /* EOL - do not finalize word */
1678 break;
1679 o_addchr(output, '\0');
1680 debug_print_list("expand_on_ifs", output, n);
1681 n = o_save_ptr(output, n);
1682 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001683 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001684 debug_print_list("expand_on_ifs[1]", output, n);
1685 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001686}
1687
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001688#if ENABLE_HUSH_TICK
1689static int process_command_subs(o_string *dest,
1690 struct in_str *input, const char *subst_end);
Eric Andersen25f27032001-04-26 23:22:31 +00001691#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001692
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001693/* Expand all variable references in given string, adding words to list[]
1694 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1695 * to be filled). This routine is extremely tricky: has to deal with
1696 * variables/parameters with whitespace, $* and $@, and constructs like
1697 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1698static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001699{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001700 /* or_mask is either 0 (normal case) or 0x80
1701 * (expansion of right-hand side of assignment == 1-element expand.
1702 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001703
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001704 char first_ch, ored_ch;
1705 int i;
1706 const char *val;
1707 char *p;
1708
1709 ored_ch = 0;
1710
1711 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1712 debug_print_list("expand_vars_to_list", output, n);
1713 n = o_save_ptr(output, n);
1714 debug_print_list("expand_vars_to_list[0]", output, n);
1715
1716 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1717#if ENABLE_HUSH_TICK
1718 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001719#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001720 o_addstr(output, arg, p - arg);
1721 debug_print_list("expand_vars_to_list[1]", output, n);
1722 arg = ++p;
1723 p = strchr(p, SPECIAL_VAR_SYMBOL);
1724
1725 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1726 /* "$@" is special. Even if quoted, it can still
1727 * expand to nothing (not even an empty string) */
1728 if ((first_ch & 0x7f) != '@')
1729 ored_ch |= first_ch;
1730 val = NULL;
1731 switch (first_ch & 0x7f) {
1732 /* Highest bit in first_ch indicates that var is double-quoted */
1733 case '$': /* pid */
1734 val = utoa(G.root_pid);
1735 break;
1736 case '!': /* bg pid */
1737 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1738 break;
1739 case '?': /* exitcode */
1740 val = utoa(G.last_return_code);
1741 break;
1742 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001743 if (arg[1] != SPECIAL_VAR_SYMBOL)
1744 /* actually, it's a ${#var} */
1745 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001746 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1747 break;
1748 case '*':
1749 case '@':
1750 i = 1;
1751 if (!G.global_argv[i])
1752 break;
1753 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1754 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1755 smallint sv = output->o_quote;
1756 /* unquoted var's contents should be globbed, so don't quote */
1757 output->o_quote = 0;
1758 while (G.global_argv[i]) {
1759 n = expand_on_ifs(output, n, G.global_argv[i]);
1760 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1761 if (G.global_argv[i++][0] && G.global_argv[i]) {
1762 /* this argv[] is not empty and not last:
1763 * put terminating NUL, start new word */
1764 o_addchr(output, '\0');
1765 debug_print_list("expand_vars_to_list[2]", output, n);
1766 n = o_save_ptr(output, n);
1767 debug_print_list("expand_vars_to_list[3]", output, n);
1768 }
1769 }
1770 output->o_quote = sv;
1771 } else
1772 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1773 * and in this case should treat it like '$*' - see 'else...' below */
1774 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1775 while (1) {
1776 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1777 if (++i >= G.global_argc)
1778 break;
1779 o_addchr(output, '\0');
1780 debug_print_list("expand_vars_to_list[4]", output, n);
1781 n = o_save_ptr(output, n);
1782 }
1783 } else { /* quoted $*: add as one word */
1784 while (1) {
1785 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1786 if (!G.global_argv[++i])
1787 break;
1788 if (G.ifs[0])
1789 o_addchr(output, G.ifs[0]);
1790 }
1791 }
1792 break;
1793 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1794 /* "Empty variable", used to make "" etc to not disappear */
1795 arg++;
1796 ored_ch = 0x80;
1797 break;
1798#if ENABLE_HUSH_TICK
1799 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1800 struct in_str input;
1801 *p = '\0';
1802 arg++;
1803//TODO: can we just stuff it into "output" directly?
1804 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1805 setup_string_in_str(&input, arg);
1806 process_command_subs(&subst_result, &input, NULL);
1807 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1808 val = subst_result.data;
1809 goto store_val;
Eric Andersen25f27032001-04-26 23:22:31 +00001810 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001811#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001812 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001813 case_default: {
1814 bool exp_len = false, exp_null = false;
1815 char *var = arg, exp_save, exp_op, *exp_word;
1816 size_t exp_off = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001817 *p = '\0';
1818 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001819
1820 /* prepare for expansions */
1821 if (var[0] == '#') {
1822 /* handle length expansion ${#var} */
1823 exp_len = true;
1824 ++var;
1825 } else {
1826 /* maybe handle parameter expansion */
1827 exp_off = strcspn(var, ":-=+?");
1828 if (!var[exp_off])
1829 exp_off = 0;
1830 if (exp_off) {
1831 exp_save = var[exp_off];
1832 exp_null = exp_save == ':';
1833 exp_word = var + exp_off;
1834 if (exp_null) ++exp_word;
1835 exp_op = *exp_word++;
1836 var[exp_off] = '\0';
1837 }
1838 }
1839
1840 /* lookup the variable in question */
1841 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00001842 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001843 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001844 if (i < G.global_argc)
1845 val = G.global_argv[i];
1846 /* else val remains NULL: $N with too big N */
1847 } else
Mike Frysinger6379bb42009-03-28 18:55:03 +00001848 val = lookup_param(var);
1849
1850 /* handle any expansions */
1851 if (exp_len) {
1852 debug_printf_expand("expand: length of '%s' = ", val);
1853 val = utoa(val ? strlen(val) : 0);
1854 debug_printf_expand("%s\n", val);
1855 } else if (exp_off) {
1856 /* we need to do an expansion */
1857 int exp_test = (!val || (exp_null && !val[0]));
1858 if (exp_op == '+')
1859 exp_test = !exp_test;
1860 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1861 exp_null ? "true" : "false", exp_test);
1862 if (exp_test) {
1863 if (exp_op == '?')
1864 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1865 else
1866 val = exp_word;
1867
1868 if (exp_op == '=') {
1869 if (isdigit(var[0]) || var[0] == '#') {
1870 maybe_die(var, "special vars cannot assign in this way");
1871 val = NULL;
1872 } else {
1873 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1874 sprintf(new_var, "%s=%s", var, val);
1875 set_local_var(new_var, -1);
1876 }
1877 }
1878 }
1879 var[exp_off] = exp_save;
1880 }
1881
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001882 arg[0] = first_ch;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001883
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001884#if ENABLE_HUSH_TICK
1885 store_val:
1886#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001887 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1888 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1889 if (val) {
1890 /* unquoted var's contents should be globbed, so don't quote */
1891 smallint sv = output->o_quote;
1892 output->o_quote = 0;
1893 n = expand_on_ifs(output, n, val);
1894 val = NULL;
1895 output->o_quote = sv;
1896 }
1897 } else { /* quoted $VAR, val will be appended below */
1898 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1899 }
1900 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001901 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001902 if (val) {
1903 o_addQstr(output, val, strlen(val));
1904 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001905 /* Do the check to avoid writing to a const string */
1906 if (p && *p != SPECIAL_VAR_SYMBOL)
1907 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001908
1909#if ENABLE_HUSH_TICK
1910 o_free(&subst_result);
1911#endif
1912 arg = ++p;
1913 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1914
1915 if (arg[0]) {
1916 debug_print_list("expand_vars_to_list[a]", output, n);
1917 /* this part is literal, and it was already pre-quoted
1918 * if needed (much earlier), do not use o_addQstr here! */
1919 o_addstr(output, arg, strlen(arg) + 1);
1920 debug_print_list("expand_vars_to_list[b]", output, n);
1921 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1922 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1923 ) {
1924 n--;
1925 /* allow to reuse list[n] later without re-growth */
1926 output->has_empty_slot = 1;
1927 } else {
1928 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00001929 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001930 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001931}
1932
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001933static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001934{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001935 int n;
1936 char **list;
1937 char **v;
1938 o_string output = NULL_O_STRING;
1939
1940 if (or_mask & 0x100) {
1941 output.o_quote = 1; /* protect against globbing for "$var" */
1942 /* (unquoted $var will temporarily switch it off) */
1943 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001944 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001945
1946 n = 0;
1947 v = argv;
1948 while (*v) {
1949 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1950 v++;
1951 }
1952 debug_print_list("expand_variables", &output, n);
1953
1954 /* output.data (malloced in one block) gets returned in "list" */
1955 list = o_finalize_list(&output, n);
1956 debug_print_strings("expand_variables[1]", list);
1957 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00001958}
1959
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001960static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001961{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001962 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00001963}
1964
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001965/* Used for expansion of right hand of assignments */
1966/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1967 * "v=/bin/c*" */
1968static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001969{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001970 char *argv[2], **list;
1971
1972 argv[0] = (char*)str;
1973 argv[1] = NULL;
1974 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1975 if (HUSH_DEBUG)
1976 if (!list[0] || list[1])
1977 bb_error_msg_and_die("BUG in varexp2");
1978 /* actually, just move string 2*sizeof(char*) bytes back */
1979 overlapping_strcpy((char*)list, list[0]);
1980 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1981 return (char*)list;
1982}
1983
1984/* Used for "eval" builtin */
1985static char* expand_strvec_to_string(char **argv)
1986{
1987 char **list;
1988
1989 list = expand_variables(argv, 0x80);
1990 /* Convert all NULs to spaces */
1991 if (list[0]) {
1992 int n = 1;
1993 while (list[n]) {
1994 if (HUSH_DEBUG)
1995 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1996 bb_error_msg_and_die("BUG in varexp3");
1997 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1998 n++;
1999 }
2000 }
2001 overlapping_strcpy((char*)list, list[0]);
2002 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2003 return (char*)list;
2004}
2005
2006static char **expand_assignments(char **argv, int count)
2007{
2008 int i;
2009 char **p = NULL;
2010 /* Expand assignments into one string each */
2011 for (i = 0; i < count; i++) {
2012 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2013 }
2014 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002015}
2016
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002017
Eric Andersen25f27032001-04-26 23:22:31 +00002018/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2019 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002020static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002021{
2022 int openfd, mode;
2023 struct redir_struct *redir;
2024
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002025 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002026 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002027 /* something went wrong in the parse. Pretend it didn't happen */
2028 continue;
2029 }
Eric Andersen25f27032001-04-26 23:22:31 +00002030 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002031 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002032 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00002033//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002034 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002035 openfd = open_or_warn(p, mode);
2036 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002037 if (openfd < 0) {
2038 /* this could get lost if stderr has been redirected, but
2039 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00002040 return 1;
2041 }
2042 } else {
2043 openfd = redir->dup;
2044 }
2045
2046 if (openfd != redir->fd) {
2047 if (squirrel && redir->fd < 3) {
2048 squirrel[redir->fd] = dup(redir->fd);
2049 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00002050 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00002051 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00002052 } else {
2053 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00002054 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002055 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002056 }
Eric Andersen25f27032001-04-26 23:22:31 +00002057 }
2058 }
2059 return 0;
2060}
2061
2062static void restore_redirects(int squirrel[])
2063{
2064 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002065 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002066 fd = squirrel[i];
2067 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002068 /* We simply die on error */
2069 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002070 }
2071 }
2072}
2073
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002074
2075#if !defined(DEBUG_CLEAN)
2076#define free_pipe_list(head, indent) free_pipe_list(head)
2077#define free_pipe(pi, indent) free_pipe(pi)
2078#endif
2079static int free_pipe_list(struct pipe *head, int indent);
2080
2081/* return code is the exit status of the pipe */
2082static int free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002083{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002084 char **p;
2085 struct command *command;
2086 struct redir_struct *r, *rnext;
2087 int a, i, ret_code = 0;
2088
2089 if (pi->stopped_cmds > 0)
2090 return ret_code;
2091 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2092 for (i = 0; i < pi->num_cmds; i++) {
2093 command = &pi->cmds[i];
2094 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2095 if (command->argv) {
2096 for (a = 0, p = command->argv; *p; a++, p++) {
2097 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2098 }
2099 free_strings(command->argv);
2100 command->argv = NULL;
2101 } else if (command->group) {
2102 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2103 ret_code = free_pipe_list(command->group, indent+3);
2104 debug_printf_clean("%s end group\n", indenter(indent));
2105 } else {
2106 debug_printf_clean("%s (nil)\n", indenter(indent));
2107 }
2108 for (r = command->redirects; r; r = rnext) {
2109 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2110 if (r->dup == -1) {
2111 /* guard against the case >$FOO, where foo is unset or blank */
2112 if (r->rd_filename) {
2113 debug_printf_clean(" %s\n", r->rd_filename);
2114 free(r->rd_filename);
2115 r->rd_filename = NULL;
2116 }
2117 } else {
2118 debug_printf_clean("&%d\n", r->dup);
2119 }
2120 rnext = r->next;
2121 free(r);
2122 }
2123 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002124 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002125 free(pi->cmds); /* children are an array, they get freed all at once */
2126 pi->cmds = NULL;
2127#if ENABLE_HUSH_JOB
2128 free(pi->cmdtext);
2129 pi->cmdtext = NULL;
2130#endif
2131 return ret_code;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002132}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002133
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002134static int free_pipe_list(struct pipe *head, int indent)
2135{
2136 int rcode = 0; /* if list has no members */
2137 struct pipe *pi, *next;
2138
2139 for (pi = head; pi; pi = next) {
2140#if HAS_KEYWORDS
2141 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2142#endif
2143 rcode = free_pipe(pi, indent);
2144 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2145 next = pi->next;
2146 /*pi->next = NULL;*/
2147 free(pi);
2148 }
2149 return rcode;
2150}
2151
2152
2153#if !BB_MMU
2154typedef struct nommu_save_t {
2155 char **new_env;
2156 char **old_env;
2157 char **argv;
2158} nommu_save_t;
2159#else
2160#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2161 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2162#define pseudo_exec(nommu_save, command, argv_expanded) \
2163 pseudo_exec(command, argv_expanded)
2164#endif
2165
Denis Vlasenko05743d72008-02-10 12:10:08 +00002166/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00002167 * Never returns.
2168 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00002169 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002170 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002171static 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 +00002172static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00002173{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002174 int rcode;
2175 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00002176 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002177
Denis Vlasenko1359da62007-04-21 23:27:30 +00002178 /* If a variable is assigned in a forest, and nobody listens,
2179 * was it ever really set?
2180 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002181 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002182 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002183
Denis Vlasenko9504e442008-10-29 01:19:15 +00002184 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002185#if BB_MMU
2186 putenv_all(new_env);
2187 free(new_env); /* optional */
2188#else
2189 nommu_save->new_env = new_env;
2190 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002191#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002192 if (argv_expanded) {
2193 argv = argv_expanded;
2194 } else {
2195 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002196#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002197 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002198#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002199 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002200
Denis Vlasenko1359da62007-04-21 23:27:30 +00002201 /*
2202 * Check if the command matches any of the builtins.
2203 * Depending on context, this might be redundant. But it's
2204 * easier to waste a few CPU cycles than it is to figure out
2205 * if this is one of those cases.
2206 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002207 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00002208 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002209 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002210 rcode = x->function(argv);
2211 fflush(stdout);
2212 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00002213 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002214 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002215
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002216 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002217#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002218 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002219 int a = find_applet_by_name(argv[0]);
2220 if (a >= 0) {
2221 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002222 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002223// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2224 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002225 }
2226 /* re-exec ourselves with the new arguments */
2227 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00002228 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002229 /* If they called chroot or otherwise made the binary no longer
2230 * executable, fall through */
2231 }
2232 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002233#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002234
Denis Vlasenkod5762932009-03-31 11:22:57 +00002235 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2236
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002237 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002238 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002239 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002240 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002241}
2242
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002243static int run_list(struct pipe *pi);
2244
Denis Vlasenko05743d72008-02-10 12:10:08 +00002245/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00002246 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002247static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002248static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002249{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002250 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002251 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002252
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002253 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00002254#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002255 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00002256#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00002257 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002258 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002259 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002260 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002261 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002262 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002263#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002264 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002265
2266 /* Can happen. See what bash does with ">foo" by itself. */
2267 debug_printf("trying to pseudo_exec null command\n");
2268 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002269}
2270
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002271#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002272static const char *get_cmdtext(struct pipe *pi)
2273{
2274 char **argv;
2275 char *p;
2276 int len;
2277
2278 /* This is subtle. ->cmdtext is created only on first backgrounding.
2279 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002280 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002281 if (pi->cmdtext)
2282 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002283 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002284 if (!argv || !argv[0]) {
2285 pi->cmdtext = xzalloc(1);
2286 return pi->cmdtext;
2287 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002288
2289 len = 0;
2290 do len += strlen(*argv) + 1; while (*++argv);
2291 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002292 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002293 do {
2294 len = strlen(*argv);
2295 memcpy(p, *argv, len);
2296 p += len;
2297 *p++ = ' ';
2298 } while (*++argv);
2299 p[-1] = '\0';
2300 return pi->cmdtext;
2301}
2302
Eric Andersenbafd94f2001-05-02 16:11:59 +00002303static void insert_bg_job(struct pipe *pi)
2304{
2305 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002306 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002307
2308 /* Linear search for the ID of the job to use */
2309 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002310 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002311 if (thejob->jobid >= pi->jobid)
2312 pi->jobid = thejob->jobid + 1;
2313
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002314 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002315 if (!G.job_list) {
2316 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002317 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002318 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002319 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002320 thejob->next = xmalloc(sizeof(*thejob));
2321 thejob = thejob->next;
2322 }
2323
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002324 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002325 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002326 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2327 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2328 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002329// TODO: do we really need to have so many fields which are just dead weight
2330// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002331 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002332 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002333 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002334 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002335 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002336
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002337 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002338 to the list of backgrounded thejobs and leave it alone */
Mike Frysinger87824e02009-03-30 00:19:30 +00002339 if (G.interactive_fd)
2340 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002341 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002342 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002343}
2344
Eric Andersenbafd94f2001-05-02 16:11:59 +00002345static void remove_bg_job(struct pipe *pi)
2346{
2347 struct pipe *prev_pipe;
2348
Denis Vlasenko87a86552008-07-29 19:43:10 +00002349 if (pi == G.job_list) {
2350 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002351 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002352 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002353 while (prev_pipe->next != pi)
2354 prev_pipe = prev_pipe->next;
2355 prev_pipe->next = pi->next;
2356 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002357 if (G.job_list)
2358 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002359 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002360 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002361}
Eric Andersen028b65b2001-06-28 01:10:11 +00002362
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002363/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002364static void delete_finished_bg_job(struct pipe *pi)
2365{
2366 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002367 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002368 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002369 free(pi);
2370}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002371#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002372
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002373/* Check to see if any processes have exited -- if they
2374 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002375static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002376{
Eric Andersenc798b072001-06-22 06:23:03 +00002377 int attributes;
2378 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002379#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002380 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002381#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002382 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002383 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002384
Denis Vlasenkod5762932009-03-31 11:22:57 +00002385 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2386
Eric Andersenc798b072001-06-22 06:23:03 +00002387 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002388 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002389 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002390
Denis Vlasenko1359da62007-04-21 23:27:30 +00002391/* Do we do this right?
2392 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002393 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002394 * [3]+ Stopped sleep 20 | false
2395 * bash-3.00# echo $?
2396 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2397 */
2398
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002399//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2400//are stopped. Testcase: "cat | cat" in a script (not on command line)
2401// + killall -STOP cat
2402
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002403 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00002404// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00002405 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002406 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002407 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002408#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002409 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002410 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002411 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2412 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002413 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002414 childpid, WTERMSIG(status), WEXITSTATUS(status));
2415 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002416 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002417 childpid, WEXITSTATUS(status));
2418#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002419 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002420 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002421 for (i = 0; i < fg_pipe->num_cmds; i++) {
2422 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2423 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002424 continue;
2425 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2426 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002427 fg_pipe->cmds[i].pid = 0;
2428 fg_pipe->alive_cmds--;
2429 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002430 /* last process gives overall exitstatus */
2431 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002432 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002433 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002434 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002435 fg_pipe->cmds[i].is_stopped = 1;
2436 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002437 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002438 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2439 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2440 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002441 /* All processes in fg pipe have exited/stopped */
2442#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002443 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002444 insert_bg_job(fg_pipe);
2445#endif
2446 return rcode;
2447 }
2448 /* There are still running processes in the fg pipe */
2449 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002450 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002451 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002452 }
2453
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002454#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002455 /* We asked to wait for bg or orphaned children */
2456 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002457 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002458 for (i = 0; i < pi->num_cmds; i++) {
2459 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002460 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002461 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002462 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002463 /* Happens when shell is used as init process (init=/bin/sh) */
2464 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002465 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002466
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002467 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002468 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002469 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002470 pi->cmds[i].pid = 0;
2471 pi->alive_cmds--;
2472 if (!pi->alive_cmds) {
Mike Frysinger87824e02009-03-30 00:19:30 +00002473 if (G.interactive_fd)
2474 printf(JOB_STATUS_FORMAT, pi->jobid,
2475 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002476 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002477 }
2478 } else {
2479 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002480 pi->cmds[i].is_stopped = 1;
2481 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002482 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002483#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002484 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002485
Denis Vlasenko1359da62007-04-21 23:27:30 +00002486 /* wait found no children or failed */
2487
2488 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002489 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002490 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002491}
2492
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002493#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002494static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2495{
2496 pid_t p;
2497 int rcode = checkjobs(fg_pipe);
2498 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002499 p = getpgid(0); /* pgid of our process */
2500 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002501 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002502 return rcode;
2503}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002504#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002505
Denis Vlasenko05743d72008-02-10 12:10:08 +00002506/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00002507 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002508 *
2509 * return code is normally -1, when the caller has to wait for children
2510 * to finish to determine the exit status of the pipe. If the pipe
2511 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002512 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002513 * return value.
2514 *
2515 * The input of the pipe is always stdin, the output is always
2516 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2517 * because it tries to avoid running the command substitution in
2518 * subshell, when that is in fact necessary. The subshell process
2519 * now has its stdout directed to the input of the appropriate pipe,
2520 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00002521 *
2522 * Returns -1 only if started some children. IOW: we have to
2523 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00002524 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002525static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002526{
2527 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002528 int nextin;
2529 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002530 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002531 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002532 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00002533 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002534 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002535 /* it is not always needed, but we aim to smaller code */
2536 int squirrel[] = { -1, -1, -1 };
2537 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002538 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00002539
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002540 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002541
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002542#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00002543 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002544#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002545 pi->alive_cmds = 1;
2546 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002547
2548 /* Check if this is a simple builtin (not part of a pipe).
2549 * Builtins within pipes have to fork anyway, and are handled in
2550 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2551 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002552 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002553
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002554#if ENABLE_HUSH_FUNCTIONS
2555 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2556 /* We "execute" function definition */
2557 bb_error_msg("here we ought to remember function definition, and go on");
2558 return EXIT_SUCCESS;
2559 }
2560#endif
2561
2562 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00002563 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002564 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002565 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002566 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00002567 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002568 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002569 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00002570 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002571 }
2572
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002573 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002574 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002575
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002576 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002577 char **new_env = NULL;
2578 char **old_env = NULL;
2579
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002580 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002581 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002582 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002583 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002584 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002585 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002586 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00002587 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002588 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00002589 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002590
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002591 /* Expand the rest into (possibly) many strings each */
2592 argv_expanded = expand_strvec_to_strvec(argv + i);
2593
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002594 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002595 if (strcmp(argv_expanded[0], x->cmd) != 0)
2596 continue;
2597 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2598 debug_printf("exec with redirects only\n");
2599 setup_redirects(command, NULL);
2600 rcode = EXIT_SUCCESS;
2601 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00002602 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002603 debug_printf("builtin inline %s\n", argv_expanded[0]);
2604 /* XXX setup_redirects acts on file descriptors, not FILEs.
2605 * This is perfect for work that comes after exec().
2606 * Is it really safe for inline use? Experimentally,
2607 * things seem to work with glibc. */
2608 setup_redirects(command, squirrel);
2609 new_env = expand_assignments(argv, command->assignment_cnt);
2610 old_env = putenv_all_and_save_old(new_env);
2611 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2612 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002613#if ENABLE_FEATURE_SH_STANDALONE
2614 clean_up_and_ret:
2615#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002616 restore_redirects(squirrel);
2617 free_strings_and_unsetenv(new_env, 1);
2618 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002619 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002620 clean_up_and_ret1:
2621 free(argv_expanded);
2622 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2623 debug_printf_exec("run_pipe return %d\n", rcode);
2624 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002625 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002626#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002627 i = find_applet_by_name(argv_expanded[0]);
2628 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2629 setup_redirects(command, squirrel);
2630 save_nofork_data(&G.nofork_save);
2631 new_env = expand_assignments(argv, command->assignment_cnt);
2632 old_env = putenv_all_and_save_old(new_env);
2633 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2634 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2635 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002636 }
2637#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002638 }
2639
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002640 /* NB: argv_expanded may already be created, and that
2641 * might include `cmd` runs! Do not rerun it! We *must*
2642 * use argv_expanded if it's non-NULL */
2643
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002644 /* Disable job control signals for shell (parent) and
2645 * for initial child code after fork */
Denis Vlasenkod5762932009-03-31 11:22:57 +00002646//// set_jobctrl_sighandler(SIG_IGN);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002647
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002648 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002649 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002650 nextin = 0;
2651
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002652 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00002653#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002654 volatile nommu_save_t nommu_save;
2655 nommu_save.new_env = NULL;
2656 nommu_save.old_env = NULL;
2657 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002658#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002659 command = &(pi->cmds[i]);
2660 if (command->argv) {
2661 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002662 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002663 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002664
2665 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002666 pipefds[0] = 0;
2667 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002668 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002669 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00002670
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002671 command->pid = BB_MMU ? fork() : vfork();
2672 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002673#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00002674 die_sleep = 0; /* let nofork's xfuncs die */
2675
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002676 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00002677 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002678 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002679 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002680 /* Don't do pgrp restore anymore on fatal signals */
2681 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002682 pgrp = pi->pgrp;
2683 if (pgrp < 0) /* true for 1st process only */
2684 pgrp = getpid();
2685 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002686 /* We do it in *every* child, not just first,
2687 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002688 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002689 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002690 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002691#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00002692 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002693 xmove_fd(pipefds[1], 1); /* write end */
2694 if (pipefds[0] > 1)
2695 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00002696 /* Like bash, explicit redirects override pipes,
2697 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002698 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00002699
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002700 /* Restore default handlers just prior to exec */
Denis Vlasenkod5762932009-03-31 11:22:57 +00002701//// set_jobctrl_sighandler(SIG_DFL);
2702//// set_misc_sighandler(SIG_DFL);
2703//// signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002704 /* Stores to nommu_save list of env vars putenv'ed
2705 * (NOMMU, on MMU we don't need that) */
2706 /* cast away volatility... */
2707 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002708 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002709 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002710 /* parent */
2711#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002712 /* Clean up after vforked child */
2713 free(nommu_save.argv);
2714 free_strings_and_unsetenv(nommu_save.new_env, 1);
2715 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002716#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002717 free(argv_expanded);
2718 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002719 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002720 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002721 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002722 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002723 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002724#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002725 /* Second and next children need to know pid of first one */
2726 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002727 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002728#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002729 }
Eric Andersen25f27032001-04-26 23:22:31 +00002730
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002731 if (i)
2732 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002733 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002734 close(pipefds[1]); /* write end */
2735 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002736 nextin = pipefds[0];
2737 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002738
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002739 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002740 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2741 return 1;
2742 }
2743
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002744 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002745 return -1;
2746}
2747
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002748#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002749static void debug_print_tree(struct pipe *pi, int lvl)
2750{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002751 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002752 [PIPE_SEQ] = "SEQ",
2753 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002754 [PIPE_OR ] = "OR" ,
2755 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002756 };
2757 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002758 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002759#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002760 [RES_IF ] = "IF" ,
2761 [RES_THEN ] = "THEN" ,
2762 [RES_ELIF ] = "ELIF" ,
2763 [RES_ELSE ] = "ELSE" ,
2764 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002765#endif
2766#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002767 [RES_FOR ] = "FOR" ,
2768 [RES_WHILE] = "WHILE",
2769 [RES_UNTIL] = "UNTIL",
2770 [RES_DO ] = "DO" ,
2771 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002772#endif
2773#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002774 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002775#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002776#if ENABLE_HUSH_CASE
2777 [RES_CASE ] = "CASE" ,
2778 [RES_MATCH] = "MATCH",
2779 [RES_CASEI] = "CASEI",
2780 [RES_ESAC ] = "ESAC" ,
2781#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002782 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002783 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002784 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002785 static const char *const GRPTYPE[] = {
2786 "()",
2787 "{}",
2788#if ENABLE_HUSH_FUNCTIONS
2789 "func()",
2790#endif
2791 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002792
2793 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002794
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002795 pin = 0;
2796 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002797 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2798 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002799 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002800 while (prn < pi->num_cmds) {
2801 struct command *command = &pi->cmds[prn];
2802 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002803
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002804 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2805 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002806 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002807 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002808 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002809 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002810 prn++;
2811 continue;
2812 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002813 if (argv) while (*argv) {
2814 fprintf(stderr, " '%s'", *argv);
2815 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002816 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002817 fprintf(stderr, "\n");
2818 prn++;
2819 }
2820 pi = pi->next;
2821 pin++;
2822 }
2823}
2824#endif
2825
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002826/* NB: called by pseudo_exec, and therefore must not modify any
2827 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002828static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002829{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002830#if ENABLE_HUSH_CASE
2831 char *case_word = NULL;
2832#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002833#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002834 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002835 char *for_varname = NULL;
2836 char **for_lcur = NULL;
2837 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002838#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002839 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002840 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002841#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002842 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002843#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002844 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002845#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002846 /*enum reserved_style*/ smallint rword = RES_NONE;
2847 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002848
Denis Vlasenko87a86552008-07-29 19:43:10 +00002849 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002850
Denis Vlasenko06810332007-05-21 23:30:54 +00002851#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002852 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002853 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2854 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002855 continue;
2856 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002857 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002858 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002859 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002860 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002861 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002862 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002863 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002864 continue;
2865 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002866 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2867 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002868 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002869 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002870 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002871 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002872 }
2873 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002874#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002875
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002876 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002877 * in order to return, no direct "return" statements please.
2878 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002879
Denis Vlasenkod5762932009-03-31 11:22:57 +00002880//TODO: needs re-thinking
2881
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002882#if ENABLE_HUSH_JOB
2883 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2884 * We are saving state before entering outermost list ("while...done")
2885 * so that ctrl-Z will correctly background _entire_ outermost list,
2886 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002887 if (++G.run_list_level == 1 && G.interactive_fd) {
2888 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002889 /* ctrl-Z forked and we are parent; or ctrl-C.
2890 * Sighandler has longjmped us here */
2891 signal(SIGINT, SIG_IGN);
2892 signal(SIGTSTP, SIG_IGN);
2893 /* Restore level (we can be coming from deep inside
2894 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002895 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002896#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002897 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002898 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002899 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002900 }
2901#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00002902//// if (G.ctrl_z_flag) {
2903//// /* ctrl-Z has forked and stored pid of the child in pi->pid.
2904//// * Remember this child as background job */
2905//// insert_bg_job(pi);
2906//// } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002907 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002908 bb_putchar('\n');
Denis Vlasenkod5762932009-03-31 11:22:57 +00002909//// }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002910 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002911 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002912 rcode = 0;
2913 goto ret;
2914 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00002915//// /* ctrl-Z handler will store pid etc in pi */
2916//// G.toplevel_list = pi;
2917//// G.ctrl_z_flag = 0;
2918////#if ENABLE_FEATURE_SH_STANDALONE
2919//// G.nofork_save.saved = 0; /* in case we will run a nofork later */
2920////#endif
2921//// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2922//// signal(SIGINT, handler_ctrl_c);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002923 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002924#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002925
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002926 /* Go through list of pipes, (maybe) executing them. */
2927 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002928 IF_HAS_KEYWORDS(rword = pi->res_word;)
2929 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002930 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2931 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002932#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002933 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002934 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002935 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002936 /* start of a loop: remember where loop starts */
2937 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002938 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002939 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002940#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002941 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002942 if (pi->followup == PIPE_SEQ)
2943 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002944 /* it is "<false> && CMD" or "<true> || CMD"
2945 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002946 continue;
2947 }
2948 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002949 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002950#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002951 if (cond_code) {
2952 if (rword == RES_THEN) {
2953 /* "if <false> THEN cmd": skip cmd */
2954 continue;
2955 }
2956 } else {
2957 if (rword == RES_ELSE || rword == RES_ELIF) {
2958 /* "if <true> then ... ELSE/ELIF cmd":
2959 * skip cmd and all following ones */
2960 break;
2961 }
2962 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002963#endif
2964#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002965 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002966 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002967 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002968
2969 static const char encoded_dollar_at[] ALIGN1 = {
2970 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2971 }; /* encoded representation of "$@" */
2972 static const char *const encoded_dollar_at_argv[] = {
2973 encoded_dollar_at, NULL
2974 }; /* argv list with one element: "$@" */
2975 char **vals;
2976
2977 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002978 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002979 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002980 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002981 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002982 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002983 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002984 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002985 debug_print_strings("for_list made from", vals);
2986 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002987 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002988 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002989 for_varname = pi->cmds[0].argv[0];
2990 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002991 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002992 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002993 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002994 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002995 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002996 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002997 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002998 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002999 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003000 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003001 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003002//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003003 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3004 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003005 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003006 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003007 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003008 if (rword == RES_DONE) {
3009 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003010 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003011#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003012#if ENABLE_HUSH_CASE
3013 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003014 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003015 continue;
3016 }
3017 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003018 char **argv;
3019
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003020 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3021 break;
3022 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003023 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003024 while (*argv) {
3025 char *pattern = expand_string_to_string(*argv);
3026 /* TODO: which FNM_xxx flags to use? */
3027 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3028 free(pattern);
3029 if (cond_code == 0) { /* match! we will execute this branch */
3030 free(case_word); /* make future "word)" stop */
3031 case_word = NULL;
3032 break;
3033 }
3034 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003035 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003036 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003037 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003038 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003039 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003040 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003041 }
3042#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003043 /* Just pressing <enter> in shell should check for jobs.
3044 * OTOH, in non-interactive shell this is useless
3045 * and only leads to extra job checks */
3046 if (pi->num_cmds == 0) {
3047 if (G.interactive_fd)
3048 goto check_jobs_and_continue;
3049 continue;
3050 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003051
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003052 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00003053 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003054 * after run_pipe() to collect any background children,
3055 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003056 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003057 {
3058 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003059#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00003060 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003061#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003062 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3063 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003064 /* we only ran a builtin: rcode is already known
3065 * and we don't need to wait for anything. */
Denis Vlasenkod5762932009-03-31 11:22:57 +00003066 check_and_run_traps();
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003067#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003068 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003069 if (G.flag_break_continue) {
3070 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003071 /* we might fall into outer *loop*,
3072 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003073 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003074 G.depth_break_continue--;
3075 if (G.depth_break_continue == 0)
3076 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003077 /* else: e.g. "continue 2" should *break* once, *then* continue */
3078 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003079 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003080 goto check_jobs_and_break;
3081 /* "continue": simulate end of loop */
3082 rword = RES_DONE;
3083 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003084 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003085#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003086 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003087 /* what does bash do with attempts to background builtins? */
3088 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003089 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3090 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkod5762932009-03-31 11:22:57 +00003091 check_and_run_traps();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003092#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003093 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003094 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003095#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003096 rcode = 0; /* EXIT_SUCCESS */
3097 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003098#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003099 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003100 /* waits for completion, then fg's main shell */
3101 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkod5762932009-03-31 11:22:57 +00003102 check_and_run_traps();
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003103 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
3104 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003105#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003106 { /* this one just waits for completion */
3107 rcode = checkjobs(pi);
Denis Vlasenkod5762932009-03-31 11:22:57 +00003108 check_and_run_traps();
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003109 debug_printf_exec(": checkjobs returned %d\n", rcode);
3110 }
Eric Andersen25f27032001-04-26 23:22:31 +00003111 }
3112 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003113 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00003114 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003115
3116 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00003117#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003118 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003119 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00003120#endif
3121#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003122 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003123 if (rcode) {
3124 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003125 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003126 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003127 }
3128 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003129 if (!rcode) {
3130 check_jobs_and_break:
3131 checkjobs(NULL);
3132 break;
3133 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003134 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003135#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003136 if ((rcode == 0 && pi->followup == PIPE_OR)
3137 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003138 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003139 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003140 }
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00003141
3142 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00003143 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003144 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003145
3146#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00003147//// if (G.ctrl_z_flag) {
3148//// /* ctrl-Z forked somewhere in the past, we are the child,
3149//// * and now we completed running the list. Exit. */
3150//////TODO: _exit?
3151//// exit(rcode);
3152//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003153 ret:
Denis Vlasenkod5762932009-03-31 11:22:57 +00003154 G.run_list_level--;
3155//// if (!G.run_list_level && G.interactive_fd) {
3156//// signal(SIGTSTP, SIG_IGN);
3157//// signal(SIGINT, SIG_IGN);
3158//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003159#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00003160 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003161#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003162 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003163 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003164 free(for_list);
3165#endif
3166#if ENABLE_HUSH_CASE
3167 free(case_word);
3168#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003169 return rcode;
3170}
3171
Eric Andersen25f27032001-04-26 23:22:31 +00003172/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003173static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003174{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003175 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003176 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003177 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003178 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003179 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003180 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003181 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00003182 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003183 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003184 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003185 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003186 return rcode;
3187}
3188
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003189
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003190/* Peek ahead in the in_str to find out if we have a "&n" construct,
3191 * as in "2>&1", that represents duplicating a file descriptor.
3192 * Return either -2 (syntax error), -1 (no &), or the number found.
3193 */
3194static int redirect_dup_num(struct in_str *input)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003195{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003196 int ch, d = 0, ok = 0;
3197 ch = i_peek(input);
3198 if (ch != '&') return -1;
3199
3200 i_getch(input); /* get the & */
3201 ch = i_peek(input);
3202 if (ch == '-') {
3203 i_getch(input);
3204 return -3; /* "-" represents "close me" */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003205 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003206 while (isdigit(ch)) {
3207 d = d*10 + (ch-'0');
3208 ok = 1;
3209 i_getch(input);
3210 ch = i_peek(input);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003211 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003212 if (ok) return d;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003213
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003214 bb_error_msg("ambiguous redirect");
3215 return -2;
Eric Andersen78a7c992001-05-15 16:30:25 +00003216}
3217
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003218/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00003219 * for file descriptor duplication, e.g., "2>&1".
3220 * Return code is 0 normally, 1 if a syntax error is detected in src.
3221 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003222static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00003223 struct in_str *input)
3224{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003225 struct command *command = ctx->command;
3226 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003227 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003228
3229 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003230 while (redir) {
3231 last_redir = redir;
3232 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00003233 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003234 redir = xzalloc(sizeof(struct redir_struct));
3235 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003236 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00003237 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003238 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003239 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003240 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003241 }
3242
Denis Vlasenko55789c62008-06-18 16:30:42 +00003243 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003244 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00003245
3246 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3247
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003248 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00003249 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003250 if (redir->dup == -2)
3251 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00003252 if (redir->dup != -1) {
3253 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00003254 * is legit; I postpone that to "run time"
3255 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00003256 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3257 } else {
3258 /* We do _not_ try to open the file that src points to,
3259 * since we need to return and let src be expanded first.
3260 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00003261 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00003262 ctx->pending_redirect = redir;
3263 }
3264 return 0;
3265}
3266
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003267
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003268static struct pipe *new_pipe(void)
3269{
Eric Andersen25f27032001-04-26 23:22:31 +00003270 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003271 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003272 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003273 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003274 return pi;
3275}
3276
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003277/* Command (member of a pipe) is complete. The only possible error here
3278 * is out of memory, in which case xmalloc exits. */
3279static int done_command(struct parse_context *ctx)
3280{
3281 /* The command is really already in the pipe structure, so
3282 * advance the pipe counter and make a new, null command. */
3283 struct pipe *pi = ctx->pipe;
3284 struct command *command = ctx->command;
3285
3286 if (command) {
3287 if (command->group == NULL
3288 && command->argv == NULL
3289 && command->redirects == NULL
3290 ) {
3291 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3292 return pi->num_cmds;
3293 }
3294 pi->num_cmds++;
3295 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3296 } else {
3297 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3298 }
3299
3300 /* Only real trickiness here is that the uncommitted
3301 * command structure is not counted in pi->num_cmds. */
3302 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3303 command = &pi->cmds[pi->num_cmds];
3304 memset(command, 0, sizeof(*command));
3305
3306 ctx->command = command;
3307 /* but ctx->pipe and ctx->list_head remain unchanged */
3308
3309 return pi->num_cmds; /* used only for 0/nonzero check */
3310}
3311
3312static void done_pipe(struct parse_context *ctx, pipe_style type)
3313{
3314 int not_null;
3315
3316 debug_printf_parse("done_pipe entered, followup %d\n", type);
3317 /* Close previous command */
3318 not_null = done_command(ctx);
3319 ctx->pipe->followup = type;
3320 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3321 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3322 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3323
3324 /* Without this check, even just <enter> on command line generates
3325 * tree of three NOPs (!). Which is harmless but annoying.
3326 * IOW: it is safe to do it unconditionally.
3327 * RES_NONE case is for "for a in; do ..." (empty IN set)
3328 * to work, possibly other cases too. */
3329 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3330 struct pipe *new_p;
3331 debug_printf_parse("done_pipe: adding new pipe: "
3332 "not_null:%d ctx->ctx_res_w:%d\n",
3333 not_null, ctx->ctx_res_w);
3334 new_p = new_pipe();
3335 ctx->pipe->next = new_p;
3336 ctx->pipe = new_p;
3337 ctx->command = NULL; /* needed! */
3338 /* RES_THEN, RES_DO etc are "sticky" -
3339 * they remain set for commands inside if/while.
3340 * This is used to control execution.
3341 * RES_FOR and RES_IN are NOT sticky (needed to support
3342 * cases where variable or value happens to match a keyword):
3343 */
3344#if ENABLE_HUSH_LOOPS
3345 if (ctx->ctx_res_w == RES_FOR
3346 || ctx->ctx_res_w == RES_IN)
3347 ctx->ctx_res_w = RES_NONE;
3348#endif
3349#if ENABLE_HUSH_CASE
3350 if (ctx->ctx_res_w == RES_MATCH)
3351 ctx->ctx_res_w = RES_CASEI;
3352#endif
3353 /* Create the memory for command, roughly:
3354 * ctx->pipe->cmds = new struct command;
3355 * ctx->command = &ctx->pipe->cmds[0];
3356 */
3357 done_command(ctx);
3358 }
3359 debug_printf_parse("done_pipe return\n");
3360}
3361
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003362static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003363{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003364 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003365 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003366 /* Create the memory for command, roughly:
3367 * ctx->pipe->cmds = new struct command;
3368 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003369 */
3370 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003371}
3372
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003373
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003374/* If a reserved word is found and processed, parse context is modified
3375 * and 1 is returned.
3376 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003377 * case, function, and select are obnoxious, save those for later.
3378 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003379#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003380struct reserved_combo {
3381 char literal[6];
3382 unsigned char res;
3383 unsigned char assignment_flag;
3384 int flag;
3385};
3386enum {
3387 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003388#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003389 FLAG_IF = (1 << RES_IF ),
3390 FLAG_THEN = (1 << RES_THEN ),
3391 FLAG_ELIF = (1 << RES_ELIF ),
3392 FLAG_ELSE = (1 << RES_ELSE ),
3393 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003394#endif
3395#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003396 FLAG_FOR = (1 << RES_FOR ),
3397 FLAG_WHILE = (1 << RES_WHILE),
3398 FLAG_UNTIL = (1 << RES_UNTIL),
3399 FLAG_DO = (1 << RES_DO ),
3400 FLAG_DONE = (1 << RES_DONE ),
3401 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003402#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003403#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003404 FLAG_MATCH = (1 << RES_MATCH),
3405 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003406#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003407 FLAG_START = (1 << RES_XXXX ),
3408};
3409
3410static const struct reserved_combo* match_reserved_word(o_string *word)
3411{
Eric Andersen25f27032001-04-26 23:22:31 +00003412 /* Mostly a list of accepted follow-up reserved words.
3413 * FLAG_END means we are done with the sequence, and are ready
3414 * to turn the compound list into a command.
3415 * FLAG_START means the word must start a new compound list.
3416 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003417 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003418#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003419 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3420 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3421 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3422 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3423 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3424 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003425#endif
3426#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003427 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3428 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3429 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3430 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3431 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3432 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003433#endif
3434#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003435 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3436 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003437#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003438 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003439 const struct reserved_combo *r;
3440
3441 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3442 if (strcmp(word->data, r->literal) == 0)
3443 return r;
3444 }
3445 return NULL;
3446}
3447static int reserved_word(o_string *word, struct parse_context *ctx)
3448{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003449#if ENABLE_HUSH_CASE
3450 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003451 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003452 };
3453#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003454 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003455
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003456 r = match_reserved_word(word);
3457 if (!r)
3458 return 0;
3459
3460 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003461#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003462 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3463 /* "case word IN ..." - IN part starts first match part */
3464 r = &reserved_match;
3465 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003466#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003467 if (r->flag == 0) { /* '!' */
3468 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003469 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003470 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003471 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003472 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003473 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003474 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003475 if (r->flag & FLAG_START) {
3476 struct parse_context *new;
3477 debug_printf("push stack\n");
3478 new = xmalloc(sizeof(*new));
3479 *new = *ctx; /* physical copy */
3480 initialize_context(ctx);
3481 ctx->stack = new;
3482 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3483 syntax(NULL);
3484 ctx->ctx_res_w = RES_SNTX;
3485 return 1;
3486 }
3487 ctx->ctx_res_w = r->res;
3488 ctx->old_flag = r->flag;
3489 if (ctx->old_flag & FLAG_END) {
3490 struct parse_context *old;
3491 debug_printf("pop stack\n");
3492 done_pipe(ctx, PIPE_SEQ);
3493 old = ctx->stack;
3494 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003495 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003496 *ctx = *old; /* physical copy */
3497 free(old);
3498 }
3499 word->o_assignment = r->assignment_flag;
3500 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003501}
Denis Vlasenko06810332007-05-21 23:30:54 +00003502#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003503
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003504//TODO: many, many callers don't check error from done_word()
3505
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003506/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003507 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003508static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003509{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003510 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003511
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003512 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003513 if (word->length == 0 && word->nonnull == 0) {
3514 debug_printf_parse("done_word return 0: true null, ignored\n");
3515 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003516 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003517 /* If this word wasn't an assignment, next ones definitely
3518 * can't be assignments. Even if they look like ones. */
3519 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3520 && word->o_assignment != WORD_IS_KEYWORD
3521 ) {
3522 word->o_assignment = NOT_ASSIGNMENT;
3523 } else {
3524 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003525 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003526 word->o_assignment = MAYBE_ASSIGNMENT;
3527 }
3528
Eric Andersen25f27032001-04-26 23:22:31 +00003529 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003530 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3531 * only if run as "bash", not "sh" */
3532 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003533 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003534 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003535 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003536 /* "{ echo foo; } echo bar" - bad */
3537 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003538 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003539 syntax(NULL);
3540 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3541 return 1;
3542 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003543#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003544#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003545 if (ctx->ctx_dsemicolon
3546 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3547 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003548 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003549 /* ctx->ctx_res_w = RES_MATCH; */
3550 ctx->ctx_dsemicolon = 0;
3551 } else
3552#endif
3553
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003554 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003555#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003556 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3557 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003558#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003559 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003560 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3561 if (reserved_word(word, ctx)) {
3562 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003563 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3564 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003565 }
Eric Andersen25f27032001-04-26 23:22:31 +00003566 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003567#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003568 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003569 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3570 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003571 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003572 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003573 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003574 char *p = word->data;
3575 while (p[0] == SPECIAL_VAR_SYMBOL
3576 && (p[1] & 0x7f) == '@'
3577 && p[2] == SPECIAL_VAR_SYMBOL
3578 ) {
3579 p += 3;
3580 }
3581 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003582 /* saw no "$@", or not only "$@" but some
3583 * real text is there too */
3584 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003585 * e.g. "", $empty"" etc to not disappear */
3586 o_addchr(word, SPECIAL_VAR_SYMBOL);
3587 o_addchr(word, SPECIAL_VAR_SYMBOL);
3588 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003589 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003590 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003591 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003592 }
Eric Andersen25f27032001-04-26 23:22:31 +00003593
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003594 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003595 ctx->pending_redirect = NULL;
3596
Denis Vlasenko06810332007-05-21 23:30:54 +00003597#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003598 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003599 /* NB: basically, this makes hush see "for v in ..." syntax as if
3600 * as it is "for v; in ...". FOR and IN become two pipe structs
3601 * in parse tree. */
3602 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003603//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003604 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003605 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003606#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003607#if ENABLE_HUSH_CASE
3608 /* Force CASE to have just one word */
3609 if (ctx->ctx_res_w == RES_CASE) {
3610 done_pipe(ctx, PIPE_SEQ);
3611 }
3612#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003613 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003614 return 0;
3615}
3616
Eric Andersen25f27032001-04-26 23:22:31 +00003617/* If a redirect is immediately preceded by a number, that number is
3618 * supposed to tell which file descriptor to redirect. This routine
3619 * looks for such preceding numbers. In an ideal world this routine
3620 * needs to handle all the following classes of redirects...
3621 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3622 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3623 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3624 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3625 * A -1 output from this program means no valid number was found, so the
3626 * caller should use the appropriate default for this redirection.
3627 */
3628static int redirect_opt_num(o_string *o)
3629{
3630 int num;
3631
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003632 if (o->length == 0)
3633 return -1;
3634 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003635 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003636 return -1;
3637 }
3638 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003639 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003640 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003641 return num;
3642}
3643
Mike Frysingerddbee972009-03-22 22:48:41 +00003644static int parse_stream(o_string *dest, struct parse_context *ctx,
3645 struct in_str *input0, const char *end_trigger);
3646
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003647#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003648static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003649{
3650 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003651 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003652
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003653 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003654/* *** NOMMU WARNING *** */
3655/* By using vfork here, we suspend parent till child exits or execs.
3656 * If child will not do it before it fills the pipe, it can block forever
3657 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003658 * Try this script:
3659 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3660 * huge=`cat TESTFILE` # will block here forever
3661 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003662 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003663 pid = BB_MMU ? fork() : vfork();
3664 if (pid < 0)
3665 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003666 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003667 if (ENABLE_HUSH_JOB)
3668 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003669 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003670 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003671 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003672#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003673 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003674#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003675 /* Process substitution is not considered to be usual
3676 * 'command execution'.
3677 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
Denis Vlasenkod5762932009-03-31 11:22:57 +00003678//// /* Not needed, we are relying on it being disabled
3679//// * everywhere outside actual command execution. */
3680 IGN_jobctrl_signals();
3681//// set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003682 /* Freeing 'head' here would break NOMMU. */
3683 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003684 }
Eric Andersen25f27032001-04-26 23:22:31 +00003685 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003686 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003687 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003688 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003689}
3690
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003691/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003692static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003693 struct in_str *input,
3694 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003695{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003696 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003697 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003698 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003699 FILE *p;
3700 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003701
Eric Andersen25f27032001-04-26 23:22:31 +00003702 initialize_context(&inner);
3703
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003704 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003705 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003706 if (retcode != 0)
3707 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003708 done_word(&result, &inner);
3709 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003710 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003711
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003712 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003713 if (p == NULL)
3714 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003715 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003716 setup_file_in_str(&pipe_str, p);
3717
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003718 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003719 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003720 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003721 if (ch == '\n') {
3722 eol_cnt++;
3723 continue;
3724 }
3725 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003726 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003727 eol_cnt--;
3728 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003729 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003730 }
3731
3732 debug_printf("done reading from pipe, pclose()ing\n");
3733 /* This is the step that wait()s for the child. Should be pretty
3734 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003735 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003736 * at the same time. That would be a lot of work, and contrary
3737 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003738 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003739 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003740 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003741 return retcode;
3742}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003743#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003744
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003745static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003746 struct in_str *input, int ch)
3747{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003748 /* dest contains characters seen prior to ( or {.
3749 * Typically it's empty, but for functions defs,
3750 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003751 int rcode;
3752 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003753 struct parse_context sub;
3754 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003755
3756 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003757#if ENABLE_HUSH_FUNCTIONS
3758 if (ch == 'F') { /* function definition? */
3759 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3760 //command->fname = dest->data;
3761 command->grp_type = GRP_FUNCTION;
3762//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3763 memset(dest, 0, sizeof(*dest));
3764 }
3765#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003766 if (command->argv /* word [word](... */
3767 || dest->length /* word(... */
3768 || dest->nonnull /* ""(... */
3769 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003770 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003771 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3772 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003773 }
3774 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003775 endch = "}";
3776 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003777 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003778 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003779 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003780 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003781 if (rcode == 0) {
3782 done_word(dest, &sub); /* finish off the final word in the subcontext */
3783 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003784 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003785 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003786 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003787 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003788 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003789}
3790
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003791#if ENABLE_HUSH_TICK
3792/* Subroutines for copying $(...) and `...` things */
3793static void add_till_backquote(o_string *dest, struct in_str *input);
3794/* '...' */
3795static void add_till_single_quote(o_string *dest, struct in_str *input)
3796{
3797 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003798 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003799 if (ch == EOF)
3800 break;
3801 if (ch == '\'')
3802 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003803 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003804 }
3805}
3806/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3807static void add_till_double_quote(o_string *dest, struct in_str *input)
3808{
3809 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003810 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003811 if (ch == '"')
3812 break;
3813 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003814 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003815 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003816 }
3817 if (ch == EOF)
3818 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003819 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003820 if (ch == '`') {
3821 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003822 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003823 continue;
3824 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003825 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003826 }
3827}
3828/* Process `cmd` - copy contents until "`" is seen. Complicated by
3829 * \` quoting.
3830 * "Within the backquoted style of command substitution, backslash
3831 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3832 * The search for the matching backquote shall be satisfied by the first
3833 * backquote found without a preceding backslash; during this search,
3834 * if a non-escaped backquote is encountered within a shell comment,
3835 * a here-document, an embedded command substitution of the $(command)
3836 * form, or a quoted string, undefined results occur. A single-quoted
3837 * or double-quoted string that begins, but does not end, within the
3838 * "`...`" sequence produces undefined results."
3839 * Example Output
3840 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3841 */
3842static void add_till_backquote(o_string *dest, struct in_str *input)
3843{
3844 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003845 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003846 if (ch == '`')
3847 break;
3848 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003849 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003850 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003851 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003852 ch = ch2;
3853 }
3854 if (ch == EOF)
3855 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003856 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003857 }
3858}
3859/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3860 * quoting and nested ()s.
3861 * "With the $(command) style of command substitution, all characters
3862 * following the open parenthesis to the matching closing parenthesis
3863 * constitute the command. Any valid shell script can be used for command,
3864 * except a script consisting solely of redirections which produces
3865 * unspecified results."
3866 * Example Output
3867 * echo $(echo '(TEST)' BEST) (TEST) BEST
3868 * echo $(echo 'TEST)' BEST) TEST) BEST
3869 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3870 */
3871static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3872{
3873 int count = 0;
3874 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003875 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003876 if (ch == EOF)
3877 break;
3878 if (ch == '(')
3879 count++;
3880 if (ch == ')')
3881 if (--count < 0)
3882 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003883 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003884 if (ch == '\'') {
3885 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003886 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003887 continue;
3888 }
3889 if (ch == '"') {
3890 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003891 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003892 continue;
3893 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003894 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3895 ch = i_getch(input);
3896 if (ch == EOF)
3897 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003898 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003899 continue;
3900 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003901 }
3902}
3903#endif /* ENABLE_HUSH_TICK */
3904
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003905/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003906static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003907{
Mike Frysinger6379bb42009-03-28 18:55:03 +00003908 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003909 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003910 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003911
3912 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003913 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003914 i_getch(input);
3915 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003916 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003917 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003918 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003919 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003920 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003921 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003922 if (!isalnum(ch) && ch != '_')
3923 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003924 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003925 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003926 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003927 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003928 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003929 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003930 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003931 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003932 o_addchr(dest, ch | quote_mask);
3933 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003934 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003935 case '$': /* pid */
3936 case '!': /* last bg pid */
3937 case '?': /* last exit code */
3938 case '#': /* number of args */
3939 case '*': /* args */
3940 case '@': /* args */
3941 goto make_one_char_var;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003942 case '{': {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003943 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003944
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003945 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3946 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003947 /* XXX maybe someone will try to escape the '}' */
Mike Frysinger6379bb42009-03-28 18:55:03 +00003948 expansion = 0;
3949 first_char = true;
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003950 all_digits = false;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003951 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003952 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003953 if (ch == '}')
3954 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003955
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003956 if (first_char) {
3957 if (ch == '#')
3958 /* ${#var}: length of var contents */
3959 goto char_ok;
3960 else if (isdigit(ch)) {
3961 all_digits = true;
3962 goto char_ok;
3963 }
3964 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00003965
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003966 if (expansion < 2 &&
3967 ((all_digits && !isdigit(ch)) ||
3968 (!all_digits && !isalnum(ch) && ch != '_')))
3969 {
Mike Frysinger6379bb42009-03-28 18:55:03 +00003970 /* handle parameter expansions
3971 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3972 */
3973 if (first_char)
3974 goto case_default;
3975 switch (ch) {
3976 case ':': /* null modifier */
3977 if (expansion == 0) {
3978 debug_printf_parse(": null modifier\n");
3979 ++expansion;
3980 break;
3981 }
3982 goto case_default;
3983
3984#if 0 /* not implemented yet :( */
3985 case '#': /* remove prefix */
3986 case '%': /* remove suffix */
3987 if (expansion == 0) {
3988 debug_printf_parse(": remove suffix/prefix\n");
3989 expansion = 2;
3990 break;
3991 }
3992 goto case_default;
3993#endif
3994
3995 case '-': /* default value */
3996 case '=': /* assign default */
3997 case '+': /* alternative */
3998 case '?': /* error indicate */
3999 debug_printf_parse(": parameter expansion\n");
4000 expansion = 2;
4001 break;
4002
4003 default:
4004 case_default:
4005 syntax("unterminated ${name}");
4006 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4007 return 1;
4008 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004009 }
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00004010
4011 char_ok:
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004012 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004013 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004014 quote_mask = 0;
Mike Frysinger6379bb42009-03-28 18:55:03 +00004015 first_char = false;
Eric Andersen25f27032001-04-26 23:22:31 +00004016 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004017 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004018 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00004019 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004020#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004021 case '(': {
4022 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004023 i_getch(input);
4024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4025 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004026 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00004027 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004028 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004029 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004030 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004031#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004032 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00004033 i_getch(input);
4034 ch = i_peek(input);
4035 if (isalnum(ch)) { /* it's $_name or $_123 */
4036 ch = '_';
4037 goto make_var;
4038 }
4039 /* else: it's $_ */
4040 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00004041 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004042 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004043 return 1;
4044 break;
4045 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004046 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004047 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004048 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004049 return 0;
4050}
4051
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004052/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004053 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
4054 * Return code is 0 if end_trigger char is met,
4055 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00004056 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004057static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004058 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004059{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00004060 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00004061 int redir_fd;
4062 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004063 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00004064 int next;
4065
Denis Vlasenkoff097622007-10-01 10:00:45 +00004066 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00004067 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00004068 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00004069
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004070 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 +00004071
Denis Vlasenko1a735862007-05-23 00:32:25 +00004072 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00004073 m = CHAR_IFS;
4074 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004075 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00004076 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004077 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00004078 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004079 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004080 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00004081 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004082 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00004083 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004084 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00004085 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004086 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004087 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004088 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00004089 debug_printf_parse("parse_stream return 1: unterminated \"\n");
4090 return 1;
4091 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004092 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004093 if ((dest->o_assignment == MAYBE_ASSIGNMENT
4094 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00004095 && ch == '='
4096 && is_assignment(dest->data)
4097 ) {
4098 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4099 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004100 continue;
4101 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004102 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004103 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004104 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004105 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00004106 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00004107 if (ch == EOF)
4108 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004109 /* If we aren't performing a substitution, treat
4110 * a newline as a command separator.
4111 * [why we don't handle it exactly like ';'? --vda] */
4112 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00004113#if ENABLE_HUSH_CASE
4114 /* "case ... in <newline> word) ..." -
4115 * newlines are ignored (but ';' wouldn't be) */
4116 if (dest->length == 0 // && argv[0] == NULL
4117 && ctx->ctx_res_w == RES_MATCH
4118 ) {
4119 continue;
4120 }
4121#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004122 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004123 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004124 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004125 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004126 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004127 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004128 /* Special case: (...word) makes last word terminate,
4129 * as if ';' is seen */
4130 if (ch == ')') {
4131 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004132//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004133 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004134 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004135 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004136 if (!HAS_KEYWORDS
4137 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
4138 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004139 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
4140 return 0;
4141 }
4142 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004143 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004144 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004145 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004146
4147 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
4148 /* ch is a special char and thus this word
4149 * cannot be an assignment: */
4150 dest->o_assignment = NOT_ASSIGNMENT;
4151 }
4152
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004153 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00004154 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00004155 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004156 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004157 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004158 if (ch == EOF || ch == '\n')
4159 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004160 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004161 }
Eric Andersen25f27032001-04-26 23:22:31 +00004162 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004163 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004164 }
4165 break;
4166 case '\\':
4167 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004168 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004169 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004170 return 1;
4171 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004172 /* bash:
4173 * "The backslash retains its special meaning [in "..."]
4174 * only when followed by one of the following characters:
4175 * $, `, ", \, or <newline>. A double quote may be quoted
4176 * within double quotes by preceding it with a backslash.
4177 * If enabled, history expansion will be performed unless
4178 * an ! appearing in double quotes is escaped using
4179 * a backslash. The backslash preceding the ! is not removed."
4180 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004181 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004182 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004183 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004184 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004185 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00004186 }
4187 } else {
4188 o_addchr(dest, '\\');
4189 o_addchr(dest, i_getch(input));
4190 }
Eric Andersen25f27032001-04-26 23:22:31 +00004191 break;
4192 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004193 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004194 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
4195 return 1;
4196 }
Eric Andersen25f27032001-04-26 23:22:31 +00004197 break;
4198 case '\'':
4199 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004200 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004201 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004202 if (ch == EOF) {
4203 syntax("unterminated '");
4204 debug_printf_parse("parse_stream return 1: unterminated '\n");
4205 return 1;
4206 }
4207 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004208 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004209 if (dest->o_assignment == NOT_ASSIGNMENT)
4210 o_addqchr(dest, ch);
4211 else
4212 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004213 }
Eric Andersen25f27032001-04-26 23:22:31 +00004214 break;
4215 case '"':
4216 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004217 shadow_quote ^= 1; /* invert */
4218 if (dest->o_assignment == NOT_ASSIGNMENT)
4219 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004220 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004221#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004222 case '`': {
4223 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004224 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004225 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004226 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004227 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00004228 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004229 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004230 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004231#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004232 case '>':
4233 redir_fd = redirect_opt_num(dest);
4234 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004235 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00004236 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004237 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004238 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004239 }
4240#if 0
4241 else if (next == '(') {
4242 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004243 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004244 return 1;
4245 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004246#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004247 setup_redirect(ctx, redir_fd, redir_style, input);
4248 break;
4249 case '<':
4250 redir_fd = redirect_opt_num(dest);
4251 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004252 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00004253 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004254 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004255 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004256 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004257 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004258 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004259 }
4260#if 0
4261 else if (next == '(') {
4262 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004263 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004264 return 1;
4265 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004266#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004267 setup_redirect(ctx, redir_fd, redir_style, input);
4268 break;
4269 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004270#if ENABLE_HUSH_CASE
4271 case_semi:
4272#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004273 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004274 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004275#if ENABLE_HUSH_CASE
4276 /* Eat multiple semicolons, detect
4277 * whether it means something special */
4278 while (1) {
4279 ch = i_peek(input);
4280 if (ch != ';')
4281 break;
4282 i_getch(input);
4283 if (ctx->ctx_res_w == RES_CASEI) {
4284 ctx->ctx_dsemicolon = 1;
4285 ctx->ctx_res_w = RES_MATCH;
4286 break;
4287 }
4288 }
4289#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004290 new_cmd:
4291 /* We just finished a cmd. New one may start
4292 * with an assignment */
4293 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004294 break;
4295 case '&':
4296 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004297 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004298 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004299 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004300 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004301 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004302 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004303 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004304 case '|':
4305 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004306#if ENABLE_HUSH_CASE
4307 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004308 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004309#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004310 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004311 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004312 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004313 } else {
4314 /* we could pick up a file descriptor choice here
4315 * with redirect_opt_num(), but bash doesn't do it.
4316 * "echo foo 2| cat" yields "foo 2". */
4317 done_command(ctx);
4318 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004319 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004320 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004321#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004322 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004323 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004324 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004325 && dest->length == 0 /* not word(... */
4326 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004327 ) {
4328 continue;
4329 }
4330#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004331#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004332 if (dest->length != 0 /* not just () but word() */
4333 && dest->nonnull == 0 /* not a"b"c() */
4334 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004335//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004336 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004337 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004338 ) {
4339 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004340 i_getch(input);
4341 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004342//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004343 ch = i_getch(input);
4344 } while (ch == ' ' || ch == '\n');
4345 if (ch != '{') {
4346 syntax("was expecting {");
4347 debug_printf_parse("parse_stream return 1\n");
4348 return 1;
4349 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004350 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004351 }
4352#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004353 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004354 if (parse_group(dest, ctx, input, ch) != 0) {
4355 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004356 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004357 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004358 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004359 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004360#if ENABLE_HUSH_CASE
4361 if (ctx->ctx_res_w == RES_MATCH)
4362 goto case_semi;
4363#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004364 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004365 /* proper use of this character is caught by end_trigger:
4366 * if we see {, we call parse_group(..., end_trigger='}')
4367 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004368 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004369 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004370 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004371 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004372 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004373 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004374 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004375 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004376 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004377 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004378 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004379 return 0;
4380}
4381
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004382static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004383{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004384 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004385 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004386}
4387
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004388static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004389{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004390 G.ifs = getenv("IFS");
4391 if (G.ifs == NULL)
4392 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004393 /* Precompute a list of 'flow through' behavior so it can be treated
4394 * quickly up front. Computation is necessary because of IFS.
4395 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004396 * The charmap[] array only really needs two bits each,
4397 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004398 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004399 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004400#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004401 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004402#else
4403 set_in_charmap("\\$\"", CHAR_SPECIAL);
4404#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004405 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004406 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004407}
4408
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004409/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004410 * from builtin_source() and builtin_eval() */
4411static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004412{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004413 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004414 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004415 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004416
Eric Andersen25f27032001-04-26 23:22:31 +00004417 do {
4418 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004419 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004420#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004421 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004422#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004423 /* We will stop & execute after each ';' or '\n'.
4424 * Example: "sleep 9999; echo TEST" + ctrl-C:
4425 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004426 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004427 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004428#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004429 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004430 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004431 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004432#endif
4433 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004434 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004435 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004436 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004437 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4438 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004439 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004440 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004441#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004442 if (ctx.old_flag != 0) {
4443 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004444 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004445 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004446#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004447 /*temp.nonnull = 0; - o_free does it below */
4448 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004449 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004450 /* Discard all unprocessed line input, force prompt on */
4451 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004452#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004453 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004454#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004455 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004456 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004457 /* loop on syntax errors, return on EOF: */
4458 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004459 return 0;
4460}
4461
Denis Vlasenko170435c2007-05-23 13:01:10 +00004462static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004463{
4464 struct in_str input;
4465 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004466 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004467}
4468
Denis Vlasenko170435c2007-05-23 13:01:10 +00004469static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004470{
4471 int rcode;
4472 struct in_str input;
4473 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004474 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004475 return rcode;
4476}
4477
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004478#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004479/* Make sure we have a controlling tty. If we get started under a job
4480 * aware app (like bash for example), make sure we are now in charge so
4481 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004482static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004483{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004484 pid_t shell_pgrp;
4485
Denis Vlasenko87a86552008-07-29 19:43:10 +00004486 shell_pgrp = getpgrp();
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004487
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004488 /* If we were ran as 'hush &',
4489 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004490 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004491 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004492 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004493 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004494 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004495
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004496 /* Ignore job-control and misc signals. */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004497//// set_jobctrl_sighandler(SIG_IGN);
4498//// set_misc_sighandler(SIG_IGN);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004499//huh? signal(SIGCHLD, SIG_IGN);
4500
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004501 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004502 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004503
4504 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004505 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004506 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004507 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004508}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004509#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004510
Denis Vlasenkod5762932009-03-31 11:22:57 +00004511static int set_mode(const char cstate, const char mode)
4512{
4513 int state = (cstate == '-' ? 1 : 0);
4514 switch (mode) {
4515 case 'n': G.fake_mode = state; break;
4516 case 'x': /*G.debug_mode = state;*/ break;
4517 default: return EXIT_FAILURE;
4518 }
4519 return EXIT_SUCCESS;
4520}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004521
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004522int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004523int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004524{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004525 static const struct variable const_shell_ver = {
4526 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004527 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004528 .max_len = 1, /* 0 can provoke free(name) */
4529 .flg_export = 1,
4530 .flg_read_only = 1,
4531 };
4532
Eric Andersen25f27032001-04-26 23:22:31 +00004533 int opt;
4534 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004535 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004536 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004537
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004538 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004539
Denis Vlasenko87a86552008-07-29 19:43:10 +00004540 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004541
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004542 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004543 G.shell_ver = const_shell_ver; /* copying struct here */
4544 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004545 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004546 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4547 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004548 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004549 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004550 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004551 if (e) while (*e) {
4552 char *value = strchr(*e, '=');
4553 if (value) { /* paranoia */
4554 cur_var->next = xzalloc(sizeof(*cur_var));
4555 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004556 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004557 cur_var->max_len = strlen(*e);
4558 cur_var->flg_export = 1;
4559 }
4560 e++;
4561 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004562 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004563 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004564
Denis Vlasenko38f63192007-01-22 09:03:07 +00004565#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004566 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004567#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004568 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004569 G.global_argc = argc;
4570 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004571 /* Initialize some more globals to non-zero values */
4572 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004573#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00004574 if (ENABLE_FEATURE_EDITING)
4575 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004576 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004577#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004578
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004579 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004580 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004581
4582 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004583 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004584 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004585 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004586 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004587 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004588 fclose(input);
4589 }
Eric Andersen25f27032001-04-26 23:22:31 +00004590 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004591 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004592
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004593 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4594 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00004595 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004596 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004597 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00004598 if (!argv[optind]) {
4599 /* -c 'script' (no params): prevent empty $0 */
4600 *--G.global_argv = argv[0];
4601 optind--;
4602 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004603 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004604 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004605 goto final_return;
4606 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004607 /* Well, we cannot just declare interactiveness,
4608 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004609 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004610 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004611 case 's':
4612 /* "-s" means "read from stdin", but this is how we always
4613 * operate, so simply do nothing here. */
4614 break;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004615 case 'n':
4616 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00004617 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004618 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004619 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004620#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004621 fprintf(stderr, "Usage: sh [FILE]...\n"
4622 " or: sh -c command [args]...\n\n");
4623 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004624#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004625 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004626#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004627 }
4628 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004629#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004630 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004631 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004632 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004633 * no arguments remaining or the -s flag given
4634 * standard input is a terminal
4635 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004636 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004637 if (argv[optind] == NULL && input == stdin
4638 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4639 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004640 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4641 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4642 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004643 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004644 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4645 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004646 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004647 G.interactive_fd = dup(STDIN_FILENO);
4648 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004649 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004650 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004651 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004652 // TODO: track & disallow any attempts of user
4653 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004654 }
Eric Andersen25f27032001-04-26 23:22:31 +00004655 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00004656 init_signal_mask();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004657 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4658 if (G.interactive_fd) {
4659 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004660 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004661 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004662 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004663 * (we reset die_sleep = 0 whereever we [v]fork) */
4664 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004665 if (setjmp(die_jmp)) {
4666 /* xfunc has failed! die die die */
4667 hush_exit(xfunc_error_retval);
4668 }
Eric Andersenada18ff2001-05-21 16:18:22 +00004669 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004670#elif ENABLE_HUSH_INTERACTIVE
4671/* no job control compiled, only prompt/line editing */
4672 if (argv[optind] == NULL && input == stdin
4673 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4674 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004675 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4676 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004677 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004678 G.interactive_fd = dup(STDIN_FILENO);
4679 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004680 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004681 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004682 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004683 if (G.interactive_fd) {
4684 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkod5762932009-03-31 11:22:57 +00004685//// set_misc_sighandler(SIG_IGN);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004686 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004687 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00004688 init_signal_mask();
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004689#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004690
Denis Vlasenko701ac182009-03-28 19:22:08 +00004691#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4692 if (G.interactive_fd) {
Mike Frysingerb2705e12009-03-23 08:44:02 +00004693 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4694 printf("Enter 'help' for a list of built-in commands.\n\n");
4695 }
Denis Vlasenko701ac182009-03-28 19:22:08 +00004696#endif
Mike Frysingerb2705e12009-03-23 08:44:02 +00004697
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004698 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004699 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004700 } else {
4701 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004702 G.global_argv = argv + optind;
4703 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004704 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004705 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004706 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004707 }
Eric Andersen25f27032001-04-26 23:22:31 +00004708
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004709 final_return:
4710
Denis Vlasenko38f63192007-01-22 09:03:07 +00004711#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004712 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004713 if (G.cwd != bb_msg_unknown)
4714 free((char*)G.cwd);
4715 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004716 while (cur_var) {
4717 struct variable *tmp = cur_var;
4718 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004719 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004720 cur_var = cur_var->next;
4721 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004722 }
Eric Andersen25f27032001-04-26 23:22:31 +00004723#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004724 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004725}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004726
4727
4728#if ENABLE_LASH
4729int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4730int lash_main(int argc, char **argv)
4731{
4732 //bb_error_msg("lash is deprecated, please use hush instead");
4733 return hush_main(argc, argv);
4734}
4735#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004736
4737
4738/*
4739 * Built-ins
4740 */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004741static int builtin_trap(char **argv)
4742{
Denis Vlasenkod5762932009-03-31 11:22:57 +00004743 int i;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004744 int sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00004745 char *new_cmd;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004746
4747 if (!G.traps)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004748 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004749
4750 if (!argv[1]) {
4751 /* No args: print all trapped. This isn't 100% correct as we should
4752 * be escaping the cmd so that it can be pasted back in ...
4753 */
4754 for (i = 0; i < NSIG; ++i)
Denis Vlasenkod5762932009-03-31 11:22:57 +00004755 if (G.traps[i])
4756 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004757 return EXIT_SUCCESS;
4758 }
4759
Denis Vlasenkod5762932009-03-31 11:22:57 +00004760 new_cmd = NULL;
4761 i = 0;
4762 /* if first arg is decimal: reset all specified */
4763 sig = bb_strtou(*++argv, NULL, 10);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004764 if (errno == 0) {
4765 int ret;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004766 set_all:
4767 ret = EXIT_SUCCESS;
Denis Vlasenkod5762932009-03-31 11:22:57 +00004768 while (*argv) {
4769 sig = get_signum(*argv++);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004770 if (sig < 0 || sig >= NSIG) {
4771 ret = EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00004772 /* mimic bash message exactly */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004773 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
4774 continue;
4775 }
4776
Denis Vlasenkod5762932009-03-31 11:22:57 +00004777 free(G.traps[sig]);
4778 G.traps[sig] = xstrdup(new_cmd);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004779
Denis Vlasenkod5762932009-03-31 11:22:57 +00004780 debug_printf("trap: setting SIG%s (%i) to '%s'",
4781 get_signame(sig), sig, G.traps[sig]);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004782
4783 /* There is no signal for 0 (EXIT) */
4784 if (sig == 0)
4785 continue;
4786
4787 if (new_cmd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00004788 sigaddset(&G.blocked_set, sig);
4789 } else {
4790 /* there was a trap handler, we are removing it
4791 * (if sig has non-DFL handling,
4792 * we don't need to do anything) */
4793 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
4794 continue;
4795 sigdelset(&G.blocked_set, sig);
4796 }
4797 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004798 }
4799 return ret;
4800 }
4801
4802 /* first arg is "-": reset all specified to default */
4803 /* first arg is "": ignore all specified */
4804 /* everything else: execute first arg upon signal */
Denis Vlasenkod5762932009-03-31 11:22:57 +00004805 if (!argv[1]) {
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004806 bb_error_msg("trap: invalid arguments");
4807 return EXIT_FAILURE;
4808 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00004809 if (LONE_DASH(*argv))
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004810 /* nothing! */;
4811 else
Denis Vlasenkod5762932009-03-31 11:22:57 +00004812 new_cmd = *argv;
4813 argv++;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004814 goto set_all;
4815}
4816
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004817static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004818{
4819 return 0;
4820}
4821
4822static int builtin_test(char **argv)
4823{
4824 int argc = 0;
4825 while (*argv) {
4826 argc++;
4827 argv++;
4828 }
4829 return test_main(argc, argv - argc);
4830}
4831
4832static int builtin_echo(char **argv)
4833{
4834 int argc = 0;
4835 while (*argv) {
4836 argc++;
4837 argv++;
4838 }
4839 return echo_main(argc, argv - argc);
4840}
4841
4842static int builtin_eval(char **argv)
4843{
4844 int rcode = EXIT_SUCCESS;
4845
4846 if (argv[1]) {
4847 char *str = expand_strvec_to_string(argv + 1);
4848 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4849 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004850 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004851 }
4852 return rcode;
4853}
4854
4855static int builtin_cd(char **argv)
4856{
4857 const char *newdir;
4858 if (argv[1] == NULL) {
4859 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4860 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4861 newdir = getenv("HOME") ? : "/";
4862 } else
4863 newdir = argv[1];
4864 if (chdir(newdir)) {
4865 printf("cd: %s: %s\n", newdir, strerror(errno));
4866 return EXIT_FAILURE;
4867 }
4868 set_cwd();
4869 return EXIT_SUCCESS;
4870}
4871
4872static int builtin_exec(char **argv)
4873{
4874 if (argv[1] == NULL)
4875 return EXIT_SUCCESS; /* bash does this */
4876 {
4877#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004878 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004879#endif
4880// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004881 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004882 /* never returns */
4883 }
4884}
4885
4886static int builtin_exit(char **argv)
4887{
4888// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4889 //puts("exit"); /* bash does it */
4890// TODO: warn if we have background jobs: "There are stopped jobs"
4891// On second consecutive 'exit', exit anyway.
4892 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004893 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004894 /* mimic bash: exit 123abc == exit 255 + error msg */
4895 xfunc_error_retval = 255;
4896 /* bash: exit -2 == exit 254, no error msg */
4897 hush_exit(xatoi(argv[1]) & 0xff);
4898}
4899
4900static int builtin_export(char **argv)
4901{
4902 const char *value;
4903 char *name = argv[1];
4904
4905 if (name == NULL) {
4906 // TODO:
4907 // ash emits: export VAR='VAL'
4908 // bash: declare -x VAR="VAL"
4909 // (both also escape as needed (quotes, $, etc))
4910 char **e = environ;
4911 if (e)
4912 while (*e)
4913 puts(*e++);
4914 return EXIT_SUCCESS;
4915 }
4916
4917 value = strchr(name, '=');
4918 if (!value) {
4919 /* They are exporting something without a =VALUE */
4920 struct variable *var;
4921
4922 var = get_local_var(name);
4923 if (var) {
4924 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004925 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004926 putenv(var->varstr);
4927 }
4928 /* bash does not return an error when trying to export
4929 * an undefined variable. Do likewise. */
4930 return EXIT_SUCCESS;
4931 }
4932
4933 set_local_var(xstrdup(name), 1);
4934 return EXIT_SUCCESS;
4935}
4936
4937#if ENABLE_HUSH_JOB
4938/* built-in 'fg' and 'bg' handler */
4939static int builtin_fg_bg(char **argv)
4940{
4941 int i, jobnum;
4942 struct pipe *pi;
4943
Denis Vlasenko87a86552008-07-29 19:43:10 +00004944 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004945 return EXIT_FAILURE;
4946 /* If they gave us no args, assume they want the last backgrounded task */
4947 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004948 for (pi = G.job_list; pi; pi = pi->next) {
4949 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004950 goto found;
4951 }
4952 }
4953 bb_error_msg("%s: no current job", argv[0]);
4954 return EXIT_FAILURE;
4955 }
4956 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4957 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4958 return EXIT_FAILURE;
4959 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004960 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004961 if (pi->jobid == jobnum) {
4962 goto found;
4963 }
4964 }
4965 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4966 return EXIT_FAILURE;
4967 found:
4968 // TODO: bash prints a string representation
4969 // of job being foregrounded (like "sleep 1 | cat")
4970 if (*argv[0] == 'f') {
4971 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004972 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004973 }
4974
4975 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004976 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4977 for (i = 0; i < pi->num_cmds; i++) {
4978 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4979 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004980 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004981 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004982
4983 i = kill(- pi->pgrp, SIGCONT);
4984 if (i < 0) {
4985 if (errno == ESRCH) {
4986 delete_finished_bg_job(pi);
4987 return EXIT_SUCCESS;
4988 } else {
4989 bb_perror_msg("kill (SIGCONT)");
4990 }
4991 }
4992
4993 if (*argv[0] == 'f') {
4994 remove_bg_job(pi);
4995 return checkjobs_and_fg_shell(pi);
4996 }
4997 return EXIT_SUCCESS;
4998}
4999#endif
5000
5001#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005002static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005003{
5004 const struct built_in_command *x;
5005
5006 printf("\nBuilt-in commands:\n");
5007 printf("-------------------\n");
5008 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5009 printf("%s\t%s\n", x->cmd, x->descr);
5010 }
5011 printf("\n\n");
5012 return EXIT_SUCCESS;
5013}
5014#endif
5015
5016#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005017static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005018{
5019 struct pipe *job;
5020 const char *status_string;
5021
Denis Vlasenko87a86552008-07-29 19:43:10 +00005022 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00005023 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005024 status_string = "Stopped";
5025 else
5026 status_string = "Running";
5027
5028 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5029 }
5030 return EXIT_SUCCESS;
5031}
5032#endif
5033
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005034static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005035{
5036 puts(set_cwd());
5037 return EXIT_SUCCESS;
5038}
5039
5040static int builtin_read(char **argv)
5041{
5042 char *string;
5043 const char *name = argv[1] ? argv[1] : "REPLY";
5044
5045 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5046 return set_local_var(string, 0);
5047}
5048
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005049/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5050 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005051 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005052 * set [-abCefhmnuvx] [-o option] [argument...]
5053 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005054 * set -- [argument...]
5055 * set -o
5056 * set +o
5057 * Implementations shall support the options in both their hyphen and
5058 * plus-sign forms. These options can also be specified as options to sh.
5059 * Examples:
5060 * Write out all variables and their values: set
5061 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5062 * Turn on the -x and -v options: set -xv
5063 * Unset all positional parameters: set --
5064 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5065 * Set the positional parameters to the expansion of x, even if x expands
5066 * with a leading '-' or '+': set -- $x
5067 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005068 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005069 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005070static int builtin_set(char **argv)
5071{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005072 int n;
5073 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005074 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005075
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005076 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005077 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00005078 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005079 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005080 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00005081 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005082
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005083 do {
5084 if (!strcmp(arg, "--")) {
5085 ++argv;
5086 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005087 }
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005088
5089 if (arg[0] == '+' || arg[0] == '-') {
5090 for (n = 1; arg[n]; ++n)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005091 if (set_mode(arg[0], arg[n]))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005092 goto error;
5093 continue;
5094 }
5095
5096 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005097 } while ((arg = *++argv) != NULL);
5098 /* Now argv[0] is 1st argument */
5099
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005100 /* Only reset global_argv if we didn't process anything */
5101 if (arg == NULL)
5102 return EXIT_SUCCESS;
5103 set_argv:
5104
Denis Vlasenko424f79b2009-03-22 14:23:34 +00005105 /* NB: G.global_argv[0] ($0) is never freed/changed */
5106 g_argv = G.global_argv;
5107 if (G.global_args_malloced) {
5108 pp = g_argv;
5109 while (*++pp)
5110 free(*pp);
5111 g_argv[1] = NULL;
5112 } else {
5113 G.global_args_malloced = 1;
5114 pp = xzalloc(sizeof(pp[0]) * 2);
5115 pp[0] = g_argv[0]; /* retain $0 */
5116 g_argv = pp;
5117 }
5118 /* This realloc's G.global_argv */
5119 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5120
5121 n = 1;
5122 while (*++pp)
5123 n++;
5124 G.global_argc = n;
5125
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005126 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005127
5128 /* Nothing known, so abort */
5129 error:
5130 bb_error_msg("set: %s: invalid option", arg);
5131 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005132}
5133
5134static int builtin_shift(char **argv)
5135{
5136 int n = 1;
5137 if (argv[1]) {
5138 n = atoi(argv[1]);
5139 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005140 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00005141 if (G.global_args_malloced) {
5142 int m = 1;
5143 while (m <= n)
5144 free(G.global_argv[m++]);
5145 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005146 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00005147 memmove(&G.global_argv[1], &G.global_argv[n+1],
5148 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005149 return EXIT_SUCCESS;
5150 }
5151 return EXIT_FAILURE;
5152}
5153
5154static int builtin_source(char **argv)
5155{
5156 FILE *input;
5157 int status;
5158
5159 if (argv[1] == NULL)
5160 return EXIT_FAILURE;
5161
5162 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00005163 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005164 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005165 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005166 return EXIT_FAILURE;
5167 }
5168 close_on_exec_on(fileno(input));
5169
5170 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005171 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005172 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00005173 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005174 status = parse_and_run_file(input);
5175 fclose(input);
5176 return status;
5177}
5178
5179static int builtin_umask(char **argv)
5180{
5181 mode_t new_umask;
5182 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005183 if (arg) {
Mike Frysinger40b8dc42009-03-29 00:50:30 +00005184 new_umask = bb_strtou(arg, NULL, 8);
5185 if (errno)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005186 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005187 } else {
5188 new_umask = umask(0);
5189 printf("%.3o\n", (unsigned) new_umask);
5190 }
5191 umask(new_umask);
5192 return EXIT_SUCCESS;
5193}
5194
Mike Frysingerd690f682009-03-30 06:50:54 +00005195/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005196static int builtin_unset(char **argv)
5197{
Mike Frysingerd690f682009-03-30 06:50:54 +00005198 size_t i;
5199 int ret;
5200 bool var = true;
5201
5202 if (!argv[1])
5203 return EXIT_SUCCESS;
5204
5205 i = 0;
5206 if (argv[1][0] == '-') {
5207 switch (argv[1][1]) {
5208 case 'v': break;
5209 case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
5210 default:
5211 bb_error_msg("unset: %s: invalid option", argv[1]);
5212 return EXIT_FAILURE;
5213 }
5214 ++i;
5215 }
5216
5217 ret = EXIT_SUCCESS;
5218 while (argv[++i]) {
5219 if (var) {
5220 if (unset_local_var(argv[i]))
5221 ret = EXIT_FAILURE;
5222 }
5223#if ENABLE_HUSH_FUNCTIONS
5224 else
5225 unset_local_func(argv[i]);
5226#endif
5227 }
5228 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005229}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005230
Mike Frysinger56bdea12009-03-28 20:01:58 +00005231/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5232static int builtin_wait(char **argv)
5233{
5234 int ret = EXIT_SUCCESS;
5235 int status;
5236
Denis Vlasenkod5762932009-03-31 11:22:57 +00005237 if (*++argv == NULL)
Mike Frysinger56bdea12009-03-28 20:01:58 +00005238 /* don't care about exit status */
Denis Vlasenkod5762932009-03-31 11:22:57 +00005239 wait(NULL);
Mike Frysinger56bdea12009-03-28 20:01:58 +00005240
Denis Vlasenkod5762932009-03-31 11:22:57 +00005241 while (*argv) {
5242 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00005243 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00005244 /* mimic bash message */
5245 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00005246 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005247 }
5248 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00005249 if (WIFSIGNALED(status))
5250 ret = 128 + WTERMSIG(status);
5251 else if (WIFEXITED(status))
5252 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00005253 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00005254 ret = EXIT_FAILURE;
5255 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00005256 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00005257 ret = 127;
5258 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00005259 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00005260 }
5261
5262 return ret;
5263}
5264
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005265#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005266static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005267{
Denis Vlasenko87a86552008-07-29 19:43:10 +00005268 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005269 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005270 return EXIT_SUCCESS; /* bash compat */
5271 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005272 G.flag_break_continue++; /* BC_BREAK = 1 */
5273 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005274 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005275 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5276 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005277 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00005278 G.flag_break_continue = BC_BREAK;
5279 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005280 }
5281 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005282 if (G.depth_of_loop < G.depth_break_continue)
5283 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005284 return EXIT_SUCCESS;
5285}
5286
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005287static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005288{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005289 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5290 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005291}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005292#endif