blob: 17673c0cbd96383b10058e85f7181a473dbd8a43 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Denis Vlasenkoa8442002008-06-14 11:00:17 +000023 * o_addchr() derived from similar w_addchar function in glibc-2.2.
Eric Andersen25f27032001-04-26 23:22:31 +000024 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko424f79b2009-03-22 14:23:34 +000025 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000027 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
Mike Frysinger25a6ca02009-03-28 13:59:26 +000039 * POSIX syntax not implemented:
Eric Andersen78a7c992001-05-15 16:30:25 +000040 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000041 * Arithmetic Expansion
42 * <(list) and >(list) Process Substitution
Eric Andersen25f27032001-04-26 23:22:31 +000043 * Here Documents ( << word )
44 * Functions
Mike Frysinger25a6ca02009-03-28 13:59:26 +000045 * Tilde Expansion
Mike Frysinger6379bb42009-03-28 18:55:03 +000046 * Parameter Expansion for substring processing ${var#word} ${var%word}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000047 *
48 * Bash stuff maybe optional enable:
49 * &> and >& redirection of stdout+stderr
50 * Brace expansion
51 * reserved words: [[ ]] function select
Mike Frysinger6379bb42009-03-28 18:55:03 +000052 * substrings ${var:1:5}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000053 *
Eric Andersen25f27032001-04-26 23:22:31 +000054 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000055 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000056 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000057 * port selected bugfixes from post-0.49 busybox lash - done?
Eric Andersen83a2ae22001-05-07 17:59:25 +000058 * change { and } from special chars to reserved words
Denis Vlasenkobcb25532008-07-28 23:04:34 +000059 * builtins: return, trap, ulimit
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +000060 * test magic exec with redirection only
Eric Andersen25f27032001-04-26 23:22:31 +000061 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000062 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000063 * propagate syntax errors, die on resource errors?
64 * continuation lines, both explicit and implicit - done?
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000065 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000066 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000067 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000068 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000069
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000070#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenko424f79b2009-03-22 14:23:34 +000071//TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
Denis Vlasenko61befda2008-11-25 01:36:03 +000072//#include "applet_tables.h" doesn't work
Denis Vlasenkobe709c22008-07-28 00:01:16 +000073#include <glob.h>
74/* #include <dmalloc.h> */
75#if ENABLE_HUSH_CASE
76#include <fnmatch.h>
77#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +000078
Denis Vlasenko424f79b2009-03-22 14:23:34 +000079#define HUSH_VER_STR "0.92"
Denis Vlasenkod01ff132007-05-02 21:40:23 +000080
Denis Vlasenko61befda2008-11-25 01:36:03 +000081#if defined SINGLE_APPLET_MAIN
82/* STANDALONE does not make sense, and won't compile */
83#undef CONFIG_FEATURE_SH_STANDALONE
84#undef ENABLE_FEATURE_SH_STANDALONE
85#undef USE_FEATURE_SH_STANDALONE
86#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87#define ENABLE_FEATURE_SH_STANDALONE 0
88#define USE_FEATURE_SH_STANDALONE(...)
89#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
90#endif
91
Denis Vlasenko05743d72008-02-10 12:10:08 +000092#if !BB_MMU && ENABLE_HUSH_TICK
93//#undef ENABLE_HUSH_TICK
94//#define ENABLE_HUSH_TICK 0
95#warning On NOMMU, hush command substitution is dangerous.
96#warning Dont use it for commands which produce lots of output.
97#warning For more info see shell/hush.c, generate_stream_from_list().
98#endif
99
Denis Vlasenko05743d72008-02-10 12:10:08 +0000100#if !ENABLE_HUSH_INTERACTIVE
101#undef ENABLE_FEATURE_EDITING
102#define ENABLE_FEATURE_EDITING 0
103#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000105#endif
106
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000107/* Do we support ANY keywords? */
108#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
109#define HAS_KEYWORDS 1
110#define IF_HAS_KEYWORDS(...) __VA_ARGS__
111#define IF_HAS_NO_KEYWORDS(...)
112#else
113#define HAS_KEYWORDS 0
114#define IF_HAS_KEYWORDS(...)
115#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
116#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000117
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000118/* Keep unconditionally on for now */
119#define HUSH_DEBUG 1
120/* In progress... */
121#define ENABLE_HUSH_FUNCTIONS 0
122
123
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000124/* If you comment out one of these below, it will be #defined later
125 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000126#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000127/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000128#define debug_printf_parse(...) do {} while (0)
129#define debug_print_tree(a, b) do {} while (0)
130#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000131#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000132#define debug_printf_jobs(...) do {} while (0)
133#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000134#define debug_printf_glob(...) do {} while (0)
135#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000136#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000137#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000138
139#ifndef debug_printf
140#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000141#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000142
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000143#ifndef debug_printf_parse
144#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000145#endif
146
147#ifndef debug_printf_exec
148#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
149#endif
150
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000151#ifndef debug_printf_env
152#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
153#endif
154
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000155#ifndef debug_printf_jobs
156#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000157#define DEBUG_JOBS 1
158#else
159#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000160#endif
161
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000162#ifndef debug_printf_expand
163#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
164#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000165#else
166#define DEBUG_EXPAND 0
167#endif
168
169#ifndef debug_printf_glob
170#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
171#define DEBUG_GLOB 1
172#else
173#define DEBUG_GLOB 0
174#endif
175
176#ifndef debug_printf_list
177#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000178#endif
179
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000180#ifndef debug_printf_subst
181#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
182#endif
183
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000184#ifndef debug_printf_clean
185/* broken, of course, but OK for testing */
186static const char *indenter(int i)
187{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000188 static const char blanks[] ALIGN1 =
189 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000190 return &blanks[sizeof(blanks) - i - 1];
191}
192#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000193#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000194#endif
195
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000196#if DEBUG_EXPAND
197static void debug_print_strings(const char *prefix, char **vv)
198{
199 fprintf(stderr, "%s:\n", prefix);
200 while (*vv)
201 fprintf(stderr, " '%s'\n", *vv++);
202}
203#else
204#define debug_print_strings(prefix, vv) ((void)0)
205#endif
206
Denis Vlasenkof962a032007-11-23 12:50:54 +0000207/*
208 * Leak hunting. Use hush_leaktool.sh for post-processing.
209 */
210#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000211/* suppress "warning: no previous prototype..." */
212void *xxmalloc(int lineno, size_t size);
213void *xxrealloc(int lineno, void *ptr, size_t size);
214char *xxstrdup(int lineno, const char *str);
215void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000216void *xxmalloc(int lineno, size_t size)
217{
218 void *ptr = xmalloc((size + 0xff) & ~0xff);
219 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
220 return ptr;
221}
222void *xxrealloc(int lineno, void *ptr, size_t size)
223{
224 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
225 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
226 return ptr;
227}
228char *xxstrdup(int lineno, const char *str)
229{
230 char *ptr = xstrdup(str);
231 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
232 return ptr;
233}
234void xxfree(void *ptr)
235{
236 fprintf(stderr, "free %p\n", ptr);
237 free(ptr);
238}
239#define xmalloc(s) xxmalloc(__LINE__, s)
240#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
241#define xstrdup(s) xxstrdup(__LINE__, s)
242#define free(p) xxfree(p)
243#endif
244
245
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000246static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000247
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000248#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000249
Denis Vlasenko5703c222008-06-15 11:49:42 +0000250#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000251#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000252
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000253typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000254 REDIRECT_INPUT = 1,
255 REDIRECT_OVERWRITE = 2,
256 REDIRECT_APPEND = 3,
257 REDIRECT_HEREIS = 4,
258 REDIRECT_IO = 5
259} redir_type;
260
Denis Vlasenko55789c62008-06-18 16:30:42 +0000261/* The descrip member of this structure is only used to make
262 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000263static const struct {
264 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000265 signed char default_fd;
266 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000267} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000268 { 0, 0, "()" },
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_RDONLY, -1, "<<" },
273 { O_RDWR, 1, "<>" }
274};
275
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000276typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000277 PIPE_SEQ = 1,
278 PIPE_AND = 2,
279 PIPE_OR = 3,
280 PIPE_BG = 4,
281} pipe_style;
282
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000283typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000284 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000285#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000286 RES_IF ,
287 RES_THEN ,
288 RES_ELIF ,
289 RES_ELSE ,
290 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000291#endif
292#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000293 RES_FOR ,
294 RES_WHILE ,
295 RES_UNTIL ,
296 RES_DO ,
297 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000298#endif
299#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000300 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000301#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000302#if ENABLE_HUSH_CASE
303 RES_CASE ,
304 /* two pseudo-keywords support contrived "case" syntax: */
305 RES_MATCH , /* "word)" */
306 RES_CASEI , /* "this command is inside CASE" */
307 RES_ESAC ,
308#endif
309 RES_XXXX ,
310 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000311} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000312
Eric Andersen25f27032001-04-26 23:22:31 +0000313struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000314 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000315 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000316 int fd; /* file descriptor being redirected */
317 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000318 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000319};
320
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000321struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000322 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000323 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000324 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000325 smallint grp_type; /* GRP_xxx */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000326 struct pipe *group; /* if non-NULL, this "prog" is {} group,
327 * subshell, or a compound statement */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000328 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000329 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000330};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000331/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
332 * and on execution these are substituted with their values.
333 * Substitution can make _several_ words out of one argv[n]!
334 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000335 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000336 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000337#define GRP_NORMAL 0
338#define GRP_SUBSHELL 1
339#if ENABLE_HUSH_FUNCTIONS
340#define GRP_FUNCTION 2
341#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000342
343struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000344 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000345 int num_cmds; /* total number of commands in job */
346 int alive_cmds; /* number of commands running (not exited) */
347 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000348#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000349 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000350 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000351 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000352#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000353 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000354 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000355 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
356 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000357};
358
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000359/* This holds pointers to the various results of parsing */
360struct parse_context {
361 struct command *command;
362 struct pipe *list_head;
363 struct pipe *pipe;
364 struct redir_struct *pending_redirect;
365#if HAS_KEYWORDS
366 smallint ctx_res_w;
367 smallint ctx_inverted; /* "! cmd | cmd" */
368#if ENABLE_HUSH_CASE
369 smallint ctx_dsemicolon; /* ";;" seen */
370#endif
371 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
372 struct parse_context *stack;
373#endif
374};
375
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000376/* On program start, environ points to initial environment.
377 * putenv adds new pointers into it, unsetenv removes them.
378 * Neither of these (de)allocates the strings.
379 * setenv allocates new strings in malloc space and does putenv,
380 * and thus setenv is unusable (leaky) for shell's purposes */
381#define setenv(...) setenv_is_leaky_dont_use()
382struct variable {
383 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000384 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000385 int max_len; /* if > 0, name is part of initial env; else name is malloced */
386 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000387 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000388};
389
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000390typedef struct o_string {
Eric Andersen25f27032001-04-26 23:22:31 +0000391 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000392 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000393 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000394 /* Misnomer! it's not "quoting", it's "protection against globbing"!
395 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000396 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000397 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000398 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000399 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000400 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000401} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000402enum {
403 MAYBE_ASSIGNMENT = 0,
404 DEFINITELY_ASSIGNMENT = 1,
405 NOT_ASSIGNMENT = 2,
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000406 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000407};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000408/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000409#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000410
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000411/* I can almost use ordinary FILE*. Is open_memstream() universally
Eric Andersen25f27032001-04-26 23:22:31 +0000412 * available? Where is it documented? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000413typedef struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000414 const char *p;
415 /* eof_flag=1: last char in ->p is really an EOF */
416 char eof_flag; /* meaningless if ->p == NULL */
417 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000418#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000419 smallint promptme;
420 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000421#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000422 FILE *file;
423 int (*get) (struct in_str *);
424 int (*peek) (struct in_str *);
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000425} in_str;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000426#define i_getch(input) ((input)->get(input))
427#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000428
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000429enum {
430 CHAR_ORDINARY = 0,
431 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
432 CHAR_IFS = 2, /* treated as ordinary if quoted */
433 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000434};
435
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000436enum {
437 BC_BREAK = 1,
438 BC_CONTINUE = 2,
439};
440
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000441
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000442/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000443/* Sorted roughly by size (smaller offsets == smaller code) */
444struct globals {
445#if ENABLE_HUSH_INTERACTIVE
446 /* 'interactive_fd' is a fd# open to ctty, if we have one
447 * _AND_ if we decided to act interactively */
448 int interactive_fd;
449 const char *PS1;
450 const char *PS2;
451#endif
452#if ENABLE_FEATURE_EDITING
453 line_input_t *line_input_state;
454#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000455 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000456 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000457#if ENABLE_HUSH_JOB
458 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000459 pid_t saved_tty_pgrp;
460 int last_jobid;
461 struct pipe *job_list;
462 struct pipe *toplevel_list;
463 smallint ctrl_z_flag;
464#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000465#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000466 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000467#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000468 smallint fake_mode;
469 /* these three support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000470 smalluint last_return_code;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000471 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000472 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000473 /* how many non-NULL argv's we have. NB: $# + 1 */
474 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000475 char **global_argv;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000476#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000477 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000478 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000479#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000480 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000483 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000484#if ENABLE_FEATURE_SH_STANDALONE
485 struct nofork_save_area nofork_save;
486#endif
487#if ENABLE_HUSH_JOB
488 sigjmp_buf toplevel_jb;
489#endif
490 unsigned char charmap[256];
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000492 struct {
493 char *cmd;
494 struct sigaction oact;
495 } *traps;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000496};
497
498#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000499/* Not #defining name to G.name - this quickly gets unwieldy
500 * (too many defines). Also, I actually prefer to see when a variable
501 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000502#define INIT_G() do { \
503 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
504} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000505
506
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000507/* Function prototypes for builtins */
508static int builtin_cd(char **argv);
509static int builtin_echo(char **argv);
510static int builtin_eval(char **argv);
511static int builtin_exec(char **argv);
512static int builtin_exit(char **argv);
513static int builtin_export(char **argv);
514#if ENABLE_HUSH_JOB
515static int builtin_fg_bg(char **argv);
516static int builtin_jobs(char **argv);
517#endif
518#if ENABLE_HUSH_HELP
519static int builtin_help(char **argv);
520#endif
521static int builtin_pwd(char **argv);
522static int builtin_read(char **argv);
523static int builtin_test(char **argv);
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000524static void handle_trap(int sig);
525static int builtin_trap(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000526static int builtin_true(char **argv);
527static int builtin_set(char **argv);
Mike Frysingerad88d5a2009-03-28 13:44:51 +0000528static int builtin_set_mode(const char, const char);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000529static int builtin_shift(char **argv);
530static int builtin_source(char **argv);
531static int builtin_umask(char **argv);
532static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000533static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000534#if ENABLE_HUSH_LOOPS
535static int builtin_break(char **argv);
536static int builtin_continue(char **argv);
537#endif
538//static int builtin_not_written(char **argv);
539
540/* Table of built-in functions. They can be forked or not, depending on
541 * context: within pipes, they fork. As simple commands, they do not.
542 * When used in non-forking context, they can change global variables
543 * in the parent shell process. If forked, of course they cannot.
544 * For example, 'unset foo | whatever' will parse and run, but foo will
545 * still be set at the end. */
546struct built_in_command {
547 const char *cmd;
548 int (*function)(char **argv);
549#if ENABLE_HUSH_HELP
550 const char *descr;
551#define BLTIN(cmd, func, help) { cmd, func, help }
552#else
553#define BLTIN(cmd, func, help) { cmd, func }
554#endif
555};
556
557/* For now, echo and test are unconditionally enabled.
558 * Maybe make it configurable? */
559static const struct built_in_command bltins[] = {
560 BLTIN("." , builtin_source, "Run commands in a file"),
561 BLTIN(":" , builtin_true, "No-op"),
562 BLTIN("[" , builtin_test, "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000563#if ENABLE_HUSH_JOB
564 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
565#endif
566#if ENABLE_HUSH_LOOPS
567 BLTIN("break" , builtin_break, "Exit from a loop"),
568#endif
569 BLTIN("cd" , builtin_cd, "Change directory"),
570#if ENABLE_HUSH_LOOPS
571 BLTIN("continue", builtin_continue, "Start new loop iteration"),
572#endif
573 BLTIN("echo" , builtin_echo, "Write to stdout"),
574 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
575 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
576 BLTIN("exit" , builtin_exit, "Exit"),
577 BLTIN("export", builtin_export, "Set environment variable"),
578#if ENABLE_HUSH_JOB
579 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
580 BLTIN("jobs" , builtin_jobs, "List active jobs"),
581#endif
582 BLTIN("pwd" , builtin_pwd, "Print current directory"),
583 BLTIN("read" , builtin_read, "Input environment variable"),
584// BLTIN("return", builtin_not_written, "Return from a function"),
585 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
586 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000587 BLTIN("test" , builtin_test, "Test condition"),
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000588 BLTIN("trap" , builtin_trap, "Trap signals"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000589// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
590 BLTIN("umask" , builtin_umask, "Set file creation mask"),
591 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Mike Frysinger56bdea12009-03-28 20:01:58 +0000592 BLTIN("wait" , builtin_wait, "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000593#if ENABLE_HUSH_HELP
594 BLTIN("help" , builtin_help, "List shell built-in commands"),
595#endif
596};
597
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000598
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000599/* Normal */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000600static void maybe_die(const char *notice, const char *msg)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000601{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000602 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000603 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000604 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Mike Frysinger6379bb42009-03-28 18:55:03 +0000605 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
606#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +0000607 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000608#endif
Mike Frysinger6379bb42009-03-28 18:55:03 +0000609 fp(msg ? "%s: %s" : notice, notice, msg);
610}
Mike Frysinger5a828452009-03-28 19:09:04 +0000611#if 1
612#define syntax(msg) maybe_die("syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000613#else
Mike Frysinger5a828452009-03-28 19:09:04 +0000614/* Debug -- trick gcc to expand __LINE__ and convert to string */
615#define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
616#define _syntax(msg, line) __syntax(msg, line)
617#define syntax(msg) _syntax(msg, __LINE__)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000618#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000619
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000620static int glob_needed(const char *s)
621{
622 while (*s) {
623 if (*s == '\\')
624 s++;
625 if (*s == '*' || *s == '[' || *s == '?')
626 return 1;
627 s++;
628 }
629 return 0;
630}
631
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000632static int is_assignment(const char *s)
633{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000634 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000635 return 0;
636 s++;
637 while (isalnum(*s) || *s == '_')
638 s++;
639 return *s == '=';
640}
641
Denis Vlasenko55789c62008-06-18 16:30:42 +0000642/* Replace each \x with x in place, return ptr past NUL. */
643static char *unbackslash(char *src)
644{
645 char *dst = src;
646 while (1) {
647 if (*src == '\\')
648 src++;
649 if ((*dst++ = *src++) == '\0')
650 break;
651 }
652 return dst;
653}
654
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000655static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000656{
657 int i;
658 unsigned count1;
659 unsigned count2;
660 char **v;
661
662 v = strings;
663 count1 = 0;
664 if (v) {
665 while (*v) {
666 count1++;
667 v++;
668 }
669 }
670 count2 = 0;
671 v = add;
672 while (*v) {
673 count2++;
674 v++;
675 }
676 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
677 v[count1 + count2] = NULL;
678 i = count2;
679 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000680 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000681 return v;
682}
683
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000684static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000685{
686 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000687 v[0] = add;
688 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000689 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000690}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000691
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000692static void putenv_all(char **strings)
693{
694 if (!strings)
695 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000696 while (*strings) {
697 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000698 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000699 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000700}
701
702static char **putenv_all_and_save_old(char **strings)
703{
704 char **old = NULL;
705 char **s = strings;
706
707 if (!strings)
708 return old;
709 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000710 char *v, *eq;
711
712 eq = strchr(*strings, '=');
713 if (eq) {
714 *eq = '\0';
715 v = getenv(*strings);
716 *eq = '=';
717 if (v) {
718 /* v points to VAL in VAR=VAL, go back to VAR */
719 v -= (eq - *strings) + 1;
720 old = add_string_to_strings(old, v);
721 }
722 }
723 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000724 }
725 putenv_all(s);
726 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000727}
728
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000729static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000730{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000731 char **v;
732
733 if (!strings)
734 return;
735
736 v = strings;
737 while (*v) {
738 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000739 debug_printf_env("unsetenv '%s'\n", *v);
740 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000741 }
742 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000743 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000744 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000745}
746
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000747static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000748{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000749 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000750}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000751
752
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000753/* Signals are grouped, we handle them in batches */
754static void set_misc_sighandler(void (*handler)(int))
755{
756 bb_signals(0
757 + (1 << SIGINT)
758 + (1 << SIGQUIT)
759 + (1 << SIGTERM)
760 , handler);
761}
762
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000763#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000764
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000765static void set_fatal_sighandler(void (*handler)(int))
766{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000767 bb_signals(0
768 + (1 << SIGILL)
769 + (1 << SIGTRAP)
770 + (1 << SIGABRT)
771 + (1 << SIGFPE)
772 + (1 << SIGBUS)
773 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000774 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000775 + (1 << SIGHUP)
776 + (1 << SIGPIPE)
777 + (1 << SIGALRM)
778 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000779}
780static void set_jobctrl_sighandler(void (*handler)(int))
781{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000782 bb_signals(0
783 + (1 << SIGTSTP)
784 + (1 << SIGTTIN)
785 + (1 << SIGTTOU)
786 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000787}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000788/* SIGCHLD is special and handled separately */
789
790static void set_every_sighandler(void (*handler)(int))
791{
792 set_fatal_sighandler(handler);
793 set_jobctrl_sighandler(handler);
794 set_misc_sighandler(handler);
795 signal(SIGCHLD, handler);
796}
797
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000798static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000799{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000800 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000801// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000802 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000803}
804
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000805static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000806{
807 pid_t pid;
808
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000809 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Mike Frysingerbfc0fae2009-03-26 18:14:16 +0000810
811 if (!BB_MMU) {
812 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
813 return;
814 }
815
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000816 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000817 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000818 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000819 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000820 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000821 if (ENABLE_HUSH_JOB)
822 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000823 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000824 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000825 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000826 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000827 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000828 /* return to nofork, it will eventually exit now,
829 * not return back to shell */
830 return;
831 }
832 /* parent */
833 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000834 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000835 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000836 /* parent needs to longjmp out of running nofork.
837 * we will "return" exitcode 0, with child put in background */
838// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000839 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000840 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000841}
842
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000843/* Restores tty foreground process group, and exits.
844 * May be called as signal handler for fatal signal
845 * (will faithfully resend signal to itself, producing correct exit state)
846 * or called directly with -EXITCODE.
847 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000848static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000849static void sigexit(int sig)
850{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000851 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000852 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000853
Denis Vlasenko87a86552008-07-29 19:43:10 +0000854#if ENABLE_HUSH_INTERACTIVE
855 if (G.interactive_fd)
856 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
857#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000858
859 /* Not a signal, just exit */
860 if (sig <= 0)
861 _exit(- sig);
862
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000863 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000864}
865
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000866#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000867
868#define set_fatal_sighandler(handler) ((void)0)
869#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000870
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000871#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000872
Mike Frysinger9f8128f2009-03-29 23:49:37 +0000873/* Restores tty foreground process group, and exits. */
874static void hush_exit(int exitcode) NORETURN;
875static void hush_exit(int exitcode)
876{
877 if (G.traps && G.traps[0].cmd)
878 handle_trap(0);
879
880 if (ENABLE_HUSH_JOB) {
881 fflush(NULL); /* flush all streams */
882 sigexit(- (exitcode & 0xff));
883 } else
884 exit(exitcode);
885}
886
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000887
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000888static const char *set_cwd(void)
889{
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000890 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
891 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000892 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000893 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000894 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
895 if (!G.cwd)
896 G.cwd = bb_msg_unknown;
897 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000898}
899
Denis Vlasenko83506862007-11-23 13:11:42 +0000900
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000901/* Get/check local shell variables */
902static struct variable *get_local_var(const char *name)
903{
904 struct variable *cur;
905 int len;
906
907 if (!name)
908 return NULL;
909 len = strlen(name);
910 for (cur = G.top_var; cur; cur = cur->next) {
911 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
912 return cur;
913 }
914 return NULL;
915}
916
917/* Basically useful version until someone wants to get fancier,
918 * see the bash man page under "Parameter Expansion" */
919static const char *lookup_param(const char *src)
920{
921 struct variable *var = get_local_var(src);
922 if (var)
923 return strchr(var->varstr, '=') + 1;
924 return NULL;
925}
926
927/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +0000928 * We take ownership of it.
929 * flg_export is used by:
930 * 0: do not export
931 * 1: export
932 * -1: if NAME is set, leave export status alone
933 * if NAME is not set, do not export
934 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000935static int set_local_var(char *str, int flg_export)
936{
937 struct variable *cur;
938 char *value;
939 int name_len;
940
941 value = strchr(str, '=');
942 if (!value) { /* not expected to ever happen? */
943 free(str);
944 return -1;
945 }
946
947 name_len = value - str + 1; /* including '=' */
948 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
949 while (1) {
950 if (strncmp(cur->varstr, str, name_len) != 0) {
951 if (!cur->next) {
952 /* Bail out. Note that now cur points
953 * to last var in linked list */
954 break;
955 }
956 cur = cur->next;
957 continue;
958 }
959 /* We found an existing var with this name */
960 *value = '\0';
961 if (cur->flg_read_only) {
962 bb_error_msg("%s: readonly variable", str);
963 free(str);
964 return -1;
965 }
966 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
967 unsetenv(str); /* just in case */
968 *value = '=';
969 if (strcmp(cur->varstr, str) == 0) {
970 free_and_exp:
971 free(str);
972 goto exp;
973 }
974 if (cur->max_len >= strlen(str)) {
975 /* This one is from startup env, reuse space */
976 strcpy(cur->varstr, str);
977 goto free_and_exp;
978 }
979 /* max_len == 0 signifies "malloced" var, which we can
980 * (and has to) free */
981 if (!cur->max_len)
982 free(cur->varstr);
983 cur->max_len = 0;
984 goto set_str_and_exp;
985 }
986
987 /* Not found - create next variable struct */
988 cur->next = xzalloc(sizeof(*cur));
989 cur = cur->next;
990
991 set_str_and_exp:
992 cur->varstr = str;
993 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +0000994 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000995 cur->flg_export = 1;
996 if (cur->flg_export) {
997 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
998 return putenv(cur->varstr);
999 }
1000 return 0;
1001}
1002
1003static void unset_local_var(const char *name)
1004{
1005 struct variable *cur;
1006 struct variable *prev = prev; /* for gcc */
1007 int name_len;
1008
1009 if (!name)
1010 return;
1011 name_len = strlen(name);
1012 cur = G.top_var;
1013 while (cur) {
1014 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1015 if (cur->flg_read_only) {
1016 bb_error_msg("%s: readonly variable", name);
1017 return;
1018 }
1019 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1020 * is ro, and we cannot reach this code on the 1st pass */
1021 prev->next = cur->next;
1022 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1023 bb_unsetenv(cur->varstr);
1024 if (!cur->max_len)
1025 free(cur->varstr);
1026 free(cur);
1027 return;
1028 }
1029 prev = cur;
1030 cur = cur->next;
1031 }
1032}
1033
1034
1035/*
1036 * in_str support
1037 */
1038static int static_get(struct in_str *i)
1039{
1040 int ch = *i->p++;
1041 if (ch == '\0') return EOF;
1042 return ch;
1043}
1044
1045static int static_peek(struct in_str *i)
1046{
1047 return *i->p;
1048}
1049
1050#if ENABLE_HUSH_INTERACTIVE
1051
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001052static void cmdedit_set_initial_prompt(void)
1053{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001054 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1055 G.PS1 = getenv("PS1");
1056 if (G.PS1 == NULL)
1057 G.PS1 = "\\w \\$ ";
1058 } else
1059 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001060}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001061
1062static const char* setup_prompt_string(int promptmode)
1063{
1064 const char *prompt_str;
1065 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001066 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1067 /* Set up the prompt */
1068 if (promptmode == 0) { /* PS1 */
1069 free((char*)G.PS1);
1070 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1071 prompt_str = G.PS1;
1072 } else
1073 prompt_str = G.PS2;
1074 } else
1075 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001076 debug_printf("result '%s'\n", prompt_str);
1077 return prompt_str;
1078}
1079
1080static void get_user_input(struct in_str *i)
1081{
1082 int r;
1083 const char *prompt_str;
1084
1085 prompt_str = setup_prompt_string(i->promptmode);
1086#if ENABLE_FEATURE_EDITING
1087 /* Enable command line editing only while a command line
1088 * is actually being read */
1089 do {
1090 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1091 } while (r == 0); /* repeat if Ctrl-C */
1092 i->eof_flag = (r < 0);
1093 if (i->eof_flag) { /* EOF/error detected */
1094 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1095 G.user_input_buf[1] = '\0';
1096 }
1097#else
1098 fputs(prompt_str, stdout);
1099 fflush(stdout);
1100 G.user_input_buf[0] = r = fgetc(i->file);
1101 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1102 i->eof_flag = (r == EOF);
1103#endif
1104 i->p = G.user_input_buf;
1105}
1106
1107#endif /* INTERACTIVE */
1108
1109/* This is the magic location that prints prompts
1110 * and gets data back from the user */
1111static int file_get(struct in_str *i)
1112{
1113 int ch;
1114
1115 /* If there is data waiting, eat it up */
1116 if (i->p && *i->p) {
1117#if ENABLE_HUSH_INTERACTIVE
1118 take_cached:
1119#endif
1120 ch = *i->p++;
1121 if (i->eof_flag && !*i->p)
1122 ch = EOF;
1123 } else {
1124 /* need to double check i->file because we might be doing something
1125 * more complicated by now, like sourcing or substituting. */
1126#if ENABLE_HUSH_INTERACTIVE
1127 if (G.interactive_fd && i->promptme && i->file == stdin) {
1128 do {
1129 get_user_input(i);
1130 } while (!*i->p); /* need non-empty line */
1131 i->promptmode = 1; /* PS2 */
1132 i->promptme = 0;
1133 goto take_cached;
1134 }
1135#endif
1136 ch = fgetc(i->file);
1137 }
1138 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1139#if ENABLE_HUSH_INTERACTIVE
1140 if (ch == '\n')
1141 i->promptme = 1;
1142#endif
1143 return ch;
1144}
1145
1146/* All the callers guarantee this routine will never be
1147 * used right after a newline, so prompting is not needed.
1148 */
1149static int file_peek(struct in_str *i)
1150{
1151 int ch;
1152 if (i->p && *i->p) {
1153 if (i->eof_flag && !i->p[1])
1154 return EOF;
1155 return *i->p;
1156 }
1157 ch = fgetc(i->file);
1158 i->eof_flag = (ch == EOF);
1159 i->peek_buf[0] = ch;
1160 i->peek_buf[1] = '\0';
1161 i->p = i->peek_buf;
1162 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1163 return ch;
1164}
1165
1166static void setup_file_in_str(struct in_str *i, FILE *f)
1167{
1168 i->peek = file_peek;
1169 i->get = file_get;
1170#if ENABLE_HUSH_INTERACTIVE
1171 i->promptme = 1;
1172 i->promptmode = 0; /* PS1 */
1173#endif
1174 i->file = f;
1175 i->p = NULL;
1176}
1177
1178static void setup_string_in_str(struct in_str *i, const char *s)
1179{
1180 i->peek = static_peek;
1181 i->get = static_get;
1182#if ENABLE_HUSH_INTERACTIVE
1183 i->promptme = 1;
1184 i->promptmode = 0; /* PS1 */
1185#endif
1186 i->p = s;
1187 i->eof_flag = 0;
1188}
1189
1190
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001191/*
1192 * o_string support
1193 */
1194#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001195
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001196static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001197{
1198 o->length = 0;
1199 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001200 if (o->data)
1201 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001202}
1203
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001204static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001205{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001206 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001207 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001208}
1209
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001210static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001211{
1212 if (o->length + len > o->maxlen) {
1213 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1214 o->data = xrealloc(o->data, 1 + o->maxlen);
1215 }
1216}
1217
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001218static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001219{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001220 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1221 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001222 o->data[o->length] = ch;
1223 o->length++;
1224 o->data[o->length] = '\0';
1225}
1226
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001227static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001228{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001229 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001230 memcpy(&o->data[o->length], str, len);
1231 o->length += len;
1232 o->data[o->length] = '\0';
1233}
1234
Denis Vlasenko55789c62008-06-18 16:30:42 +00001235static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1236{
1237 while (len) {
1238 o_addchr(o, *str);
1239 if (*str++ == '\\'
1240 && (*str != '*' && *str != '?' && *str != '[')
1241 ) {
1242 o_addchr(o, '\\');
1243 }
1244 len--;
1245 }
1246}
1247
Eric Andersen25f27032001-04-26 23:22:31 +00001248/* My analysis of quoting semantics tells me that state information
1249 * is associated with a destination, not a source.
1250 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001251static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001252{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001253 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001254 char *found = strchr("*?[\\", ch);
1255 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001256 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001257 o_grow_by(o, sz);
1258 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001259 o->data[o->length] = '\\';
1260 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001261 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001262 o->data[o->length] = ch;
1263 o->length++;
1264 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001265}
1266
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001267static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001268{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001269 int sz = 1;
1270 if (o->o_quote && strchr("*?[\\", ch)) {
1271 sz++;
1272 o->data[o->length] = '\\';
1273 o->length++;
1274 }
1275 o_grow_by(o, sz);
1276 o->data[o->length] = ch;
1277 o->length++;
1278 o->data[o->length] = '\0';
1279}
1280
1281static void o_addQstr(o_string *o, const char *str, int len)
1282{
1283 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001284 o_addstr(o, str, len);
1285 return;
1286 }
1287 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001288 char ch;
1289 int sz;
1290 int ordinary_cnt = strcspn(str, "*?[\\");
1291 if (ordinary_cnt > len) /* paranoia */
1292 ordinary_cnt = len;
1293 o_addstr(o, str, ordinary_cnt);
1294 if (ordinary_cnt == len)
1295 return;
1296 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001297 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001298
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001299 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001300 sz = 1;
1301 if (ch) { /* it is necessarily one of "*?[\\" */
1302 sz++;
1303 o->data[o->length] = '\\';
1304 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001305 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001306 o_grow_by(o, sz);
1307 o->data[o->length] = ch;
1308 o->length++;
1309 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001310 }
1311}
1312
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001313/* A special kind of o_string for $VAR and `cmd` expansion.
1314 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001315 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001316 * list[i] contains an INDEX (int!) into this string data.
1317 * It means that if list[] needs to grow, data needs to be moved higher up
1318 * but list[i]'s need not be modified.
1319 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001320 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001321 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1322 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001323#if DEBUG_EXPAND || DEBUG_GLOB
1324static void debug_print_list(const char *prefix, o_string *o, int n)
1325{
1326 char **list = (char**)o->data;
1327 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1328 int i = 0;
1329 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1330 prefix, list, n, string_start, o->length, o->maxlen);
1331 while (i < n) {
1332 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1333 o->data + (int)list[i] + string_start,
1334 o->data + (int)list[i] + string_start);
1335 i++;
1336 }
1337 if (n) {
1338 const char *p = o->data + (int)list[n - 1] + string_start;
Mike Frysingerd006edb2009-03-28 12:43:53 +00001339 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001340 }
1341}
1342#else
1343#define debug_print_list(prefix, o, n) ((void)0)
1344#endif
1345
1346/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1347 * in list[n] so that it points past last stored byte so far.
1348 * It returns n+1. */
1349static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001350{
1351 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001352 int string_start;
1353 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001354
1355 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001356 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1357 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001358 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001359 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001360 /* list[n] points to string_start, make space for 16 more pointers */
1361 o->maxlen += 0x10 * sizeof(list[0]);
1362 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001363 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001364 memmove(list + n + 0x10, list + n, string_len);
1365 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001366 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001367 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001368 } else {
1369 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001370 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1371 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001372 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001373 o->has_empty_slot = 0;
1374 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001375 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001376 return n + 1;
1377}
1378
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001379/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001380static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001381{
1382 char **list = (char**)o->data;
1383 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1384
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001385 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001386}
1387
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001388/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001389 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001390static int o_glob(o_string *o, int n)
1391{
1392 glob_t globdata;
1393 int gr;
1394 char *pattern;
1395
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001396 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001397 if (!o->data)
1398 return o_save_ptr_helper(o, n);
1399 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001400 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001401 if (!glob_needed(pattern)) {
1402 literal:
1403 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001404 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001405 return o_save_ptr_helper(o, n);
1406 }
1407
1408 memset(&globdata, 0, sizeof(globdata));
1409 gr = glob(pattern, 0, NULL, &globdata);
1410 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1411 if (gr == GLOB_NOSPACE)
1412 bb_error_msg_and_die("out of memory during glob");
1413 if (gr == GLOB_NOMATCH) {
1414 globfree(&globdata);
1415 goto literal;
1416 }
1417 if (gr != 0) { /* GLOB_ABORTED ? */
1418//TODO: testcase for bad glob pattern behavior
1419 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1420 }
1421 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1422 char **argv = globdata.gl_pathv;
1423 o->length = pattern - o->data; /* "forget" pattern */
1424 while (1) {
1425 o_addstr(o, *argv, strlen(*argv) + 1);
1426 n = o_save_ptr_helper(o, n);
1427 argv++;
1428 if (!*argv)
1429 break;
1430 }
1431 }
1432 globfree(&globdata);
1433 if (DEBUG_GLOB)
1434 debug_print_list("o_glob returning", o, n);
1435 return n;
1436}
1437
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001438/* If o->o_glob == 1, glob the string so far remembered.
1439 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001440static int o_save_ptr(o_string *o, int n)
1441{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001442 if (o->o_glob) { /* if globbing is requested */
1443 /* If o->has_empty_slot, list[n] was already globbed
1444 * (if it was requested back then when it was filled)
1445 * so don't do that again! */
1446 if (!o->has_empty_slot)
1447 return o_glob(o, n); /* o_save_ptr_helper is inside */
1448 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001449 return o_save_ptr_helper(o, n);
1450}
1451
1452/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001453static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001454{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001455 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001456 int string_start;
1457
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001458 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1459 if (DEBUG_EXPAND)
1460 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001461 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001462 list = (char**)o->data;
1463 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1464 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001465 while (n) {
1466 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001467 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001468 }
1469 return list;
1470}
1471
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001472
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001473/* expand_strvec_to_strvec() takes a list of strings, expands
1474 * all variable references within and returns a pointer to
1475 * a list of expanded strings, possibly with larger number
1476 * of strings. (Think VAR="a b"; echo $VAR).
1477 * This new list is allocated as a single malloc block.
1478 * NULL-terminated list of char* pointers is at the beginning of it,
1479 * followed by strings themself.
1480 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001481
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001482/* Store given string, finalizing the word and starting new one whenever
1483 * we encounter IFS char(s). This is used for expanding variable values.
1484 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1485static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001486{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001487 while (1) {
1488 int word_len = strcspn(str, G.ifs);
1489 if (word_len) {
1490 if (output->o_quote || !output->o_glob)
1491 o_addQstr(output, str, word_len);
1492 else /* protect backslashes against globbing up :) */
1493 o_addstr_duplicate_backslash(output, str, word_len);
1494 str += word_len;
1495 }
1496 if (!*str) /* EOL - do not finalize word */
1497 break;
1498 o_addchr(output, '\0');
1499 debug_print_list("expand_on_ifs", output, n);
1500 n = o_save_ptr(output, n);
1501 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001502 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001503 debug_print_list("expand_on_ifs[1]", output, n);
1504 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001505}
1506
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001507#if ENABLE_HUSH_TICK
1508static int process_command_subs(o_string *dest,
1509 struct in_str *input, const char *subst_end);
Eric Andersen25f27032001-04-26 23:22:31 +00001510#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001511
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001512/* Expand all variable references in given string, adding words to list[]
1513 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1514 * to be filled). This routine is extremely tricky: has to deal with
1515 * variables/parameters with whitespace, $* and $@, and constructs like
1516 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1517static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001518{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001519 /* or_mask is either 0 (normal case) or 0x80
1520 * (expansion of right-hand side of assignment == 1-element expand.
1521 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001522
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001523 char first_ch, ored_ch;
1524 int i;
1525 const char *val;
1526 char *p;
1527
1528 ored_ch = 0;
1529
1530 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1531 debug_print_list("expand_vars_to_list", output, n);
1532 n = o_save_ptr(output, n);
1533 debug_print_list("expand_vars_to_list[0]", output, n);
1534
1535 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1536#if ENABLE_HUSH_TICK
1537 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001538#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001539 o_addstr(output, arg, p - arg);
1540 debug_print_list("expand_vars_to_list[1]", output, n);
1541 arg = ++p;
1542 p = strchr(p, SPECIAL_VAR_SYMBOL);
1543
1544 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1545 /* "$@" is special. Even if quoted, it can still
1546 * expand to nothing (not even an empty string) */
1547 if ((first_ch & 0x7f) != '@')
1548 ored_ch |= first_ch;
1549 val = NULL;
1550 switch (first_ch & 0x7f) {
1551 /* Highest bit in first_ch indicates that var is double-quoted */
1552 case '$': /* pid */
1553 val = utoa(G.root_pid);
1554 break;
1555 case '!': /* bg pid */
1556 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1557 break;
1558 case '?': /* exitcode */
1559 val = utoa(G.last_return_code);
1560 break;
1561 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001562 if (arg[1] != SPECIAL_VAR_SYMBOL)
1563 /* actually, it's a ${#var} */
1564 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001565 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1566 break;
1567 case '*':
1568 case '@':
1569 i = 1;
1570 if (!G.global_argv[i])
1571 break;
1572 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1573 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1574 smallint sv = output->o_quote;
1575 /* unquoted var's contents should be globbed, so don't quote */
1576 output->o_quote = 0;
1577 while (G.global_argv[i]) {
1578 n = expand_on_ifs(output, n, G.global_argv[i]);
1579 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1580 if (G.global_argv[i++][0] && G.global_argv[i]) {
1581 /* this argv[] is not empty and not last:
1582 * put terminating NUL, start new word */
1583 o_addchr(output, '\0');
1584 debug_print_list("expand_vars_to_list[2]", output, n);
1585 n = o_save_ptr(output, n);
1586 debug_print_list("expand_vars_to_list[3]", output, n);
1587 }
1588 }
1589 output->o_quote = sv;
1590 } else
1591 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1592 * and in this case should treat it like '$*' - see 'else...' below */
1593 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1594 while (1) {
1595 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1596 if (++i >= G.global_argc)
1597 break;
1598 o_addchr(output, '\0');
1599 debug_print_list("expand_vars_to_list[4]", output, n);
1600 n = o_save_ptr(output, n);
1601 }
1602 } else { /* quoted $*: add as one word */
1603 while (1) {
1604 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1605 if (!G.global_argv[++i])
1606 break;
1607 if (G.ifs[0])
1608 o_addchr(output, G.ifs[0]);
1609 }
1610 }
1611 break;
1612 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1613 /* "Empty variable", used to make "" etc to not disappear */
1614 arg++;
1615 ored_ch = 0x80;
1616 break;
1617#if ENABLE_HUSH_TICK
1618 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1619 struct in_str input;
1620 *p = '\0';
1621 arg++;
1622//TODO: can we just stuff it into "output" directly?
1623 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1624 setup_string_in_str(&input, arg);
1625 process_command_subs(&subst_result, &input, NULL);
1626 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1627 val = subst_result.data;
1628 goto store_val;
Eric Andersen25f27032001-04-26 23:22:31 +00001629 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001630#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001631 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001632 case_default: {
1633 bool exp_len = false, exp_null = false;
1634 char *var = arg, exp_save, exp_op, *exp_word;
1635 size_t exp_off = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001636 *p = '\0';
1637 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001638
1639 /* prepare for expansions */
1640 if (var[0] == '#') {
1641 /* handle length expansion ${#var} */
1642 exp_len = true;
1643 ++var;
1644 } else {
1645 /* maybe handle parameter expansion */
1646 exp_off = strcspn(var, ":-=+?");
1647 if (!var[exp_off])
1648 exp_off = 0;
1649 if (exp_off) {
1650 exp_save = var[exp_off];
1651 exp_null = exp_save == ':';
1652 exp_word = var + exp_off;
1653 if (exp_null) ++exp_word;
1654 exp_op = *exp_word++;
1655 var[exp_off] = '\0';
1656 }
1657 }
1658
1659 /* lookup the variable in question */
1660 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00001661 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001662 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001663 if (i < G.global_argc)
1664 val = G.global_argv[i];
1665 /* else val remains NULL: $N with too big N */
1666 } else
Mike Frysinger6379bb42009-03-28 18:55:03 +00001667 val = lookup_param(var);
1668
1669 /* handle any expansions */
1670 if (exp_len) {
1671 debug_printf_expand("expand: length of '%s' = ", val);
1672 val = utoa(val ? strlen(val) : 0);
1673 debug_printf_expand("%s\n", val);
1674 } else if (exp_off) {
1675 /* we need to do an expansion */
1676 int exp_test = (!val || (exp_null && !val[0]));
1677 if (exp_op == '+')
1678 exp_test = !exp_test;
1679 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1680 exp_null ? "true" : "false", exp_test);
1681 if (exp_test) {
1682 if (exp_op == '?')
1683 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1684 else
1685 val = exp_word;
1686
1687 if (exp_op == '=') {
1688 if (isdigit(var[0]) || var[0] == '#') {
1689 maybe_die(var, "special vars cannot assign in this way");
1690 val = NULL;
1691 } else {
1692 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1693 sprintf(new_var, "%s=%s", var, val);
1694 set_local_var(new_var, -1);
1695 }
1696 }
1697 }
1698 var[exp_off] = exp_save;
1699 }
1700
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001701 arg[0] = first_ch;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001702
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001703#if ENABLE_HUSH_TICK
1704 store_val:
1705#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001706 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1707 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1708 if (val) {
1709 /* unquoted var's contents should be globbed, so don't quote */
1710 smallint sv = output->o_quote;
1711 output->o_quote = 0;
1712 n = expand_on_ifs(output, n, val);
1713 val = NULL;
1714 output->o_quote = sv;
1715 }
1716 } else { /* quoted $VAR, val will be appended below */
1717 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1718 }
1719 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001720 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001721 if (val) {
1722 o_addQstr(output, val, strlen(val));
1723 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00001724 /* Do the check to avoid writing to a const string */
1725 if (p && *p != SPECIAL_VAR_SYMBOL)
1726 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001727
1728#if ENABLE_HUSH_TICK
1729 o_free(&subst_result);
1730#endif
1731 arg = ++p;
1732 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1733
1734 if (arg[0]) {
1735 debug_print_list("expand_vars_to_list[a]", output, n);
1736 /* this part is literal, and it was already pre-quoted
1737 * if needed (much earlier), do not use o_addQstr here! */
1738 o_addstr(output, arg, strlen(arg) + 1);
1739 debug_print_list("expand_vars_to_list[b]", output, n);
1740 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1741 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1742 ) {
1743 n--;
1744 /* allow to reuse list[n] later without re-growth */
1745 output->has_empty_slot = 1;
1746 } else {
1747 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00001748 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001749 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001750}
1751
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001752static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001753{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754 int n;
1755 char **list;
1756 char **v;
1757 o_string output = NULL_O_STRING;
1758
1759 if (or_mask & 0x100) {
1760 output.o_quote = 1; /* protect against globbing for "$var" */
1761 /* (unquoted $var will temporarily switch it off) */
1762 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001763 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001764
1765 n = 0;
1766 v = argv;
1767 while (*v) {
1768 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1769 v++;
1770 }
1771 debug_print_list("expand_variables", &output, n);
1772
1773 /* output.data (malloced in one block) gets returned in "list" */
1774 list = o_finalize_list(&output, n);
1775 debug_print_strings("expand_variables[1]", list);
1776 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00001777}
1778
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001779static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001780{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001781 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00001782}
1783
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001784/* Used for expansion of right hand of assignments */
1785/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1786 * "v=/bin/c*" */
1787static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001788{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001789 char *argv[2], **list;
1790
1791 argv[0] = (char*)str;
1792 argv[1] = NULL;
1793 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1794 if (HUSH_DEBUG)
1795 if (!list[0] || list[1])
1796 bb_error_msg_and_die("BUG in varexp2");
1797 /* actually, just move string 2*sizeof(char*) bytes back */
1798 overlapping_strcpy((char*)list, list[0]);
1799 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1800 return (char*)list;
1801}
1802
1803/* Used for "eval" builtin */
1804static char* expand_strvec_to_string(char **argv)
1805{
1806 char **list;
1807
1808 list = expand_variables(argv, 0x80);
1809 /* Convert all NULs to spaces */
1810 if (list[0]) {
1811 int n = 1;
1812 while (list[n]) {
1813 if (HUSH_DEBUG)
1814 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1815 bb_error_msg_and_die("BUG in varexp3");
1816 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1817 n++;
1818 }
1819 }
1820 overlapping_strcpy((char*)list, list[0]);
1821 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1822 return (char*)list;
1823}
1824
1825static char **expand_assignments(char **argv, int count)
1826{
1827 int i;
1828 char **p = NULL;
1829 /* Expand assignments into one string each */
1830 for (i = 0; i < count; i++) {
1831 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1832 }
1833 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00001834}
1835
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001836
Eric Andersen25f27032001-04-26 23:22:31 +00001837/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1838 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001839static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001840{
1841 int openfd, mode;
1842 struct redir_struct *redir;
1843
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001844 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001845 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001846 /* something went wrong in the parse. Pretend it didn't happen */
1847 continue;
1848 }
Eric Andersen25f27032001-04-26 23:22:31 +00001849 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001850 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001851 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001852//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001853 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001854 openfd = open_or_warn(p, mode);
1855 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001856 if (openfd < 0) {
1857 /* this could get lost if stderr has been redirected, but
1858 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001859 return 1;
1860 }
1861 } else {
1862 openfd = redir->dup;
1863 }
1864
1865 if (openfd != redir->fd) {
1866 if (squirrel && redir->fd < 3) {
1867 squirrel[redir->fd] = dup(redir->fd);
1868 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001869 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001870 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001871 } else {
1872 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001873 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001874 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001875 }
Eric Andersen25f27032001-04-26 23:22:31 +00001876 }
1877 }
1878 return 0;
1879}
1880
1881static void restore_redirects(int squirrel[])
1882{
1883 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001884 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001885 fd = squirrel[i];
1886 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001887 /* We simply die on error */
1888 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001889 }
1890 }
1891}
1892
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001893
1894#if !defined(DEBUG_CLEAN)
1895#define free_pipe_list(head, indent) free_pipe_list(head)
1896#define free_pipe(pi, indent) free_pipe(pi)
1897#endif
1898static int free_pipe_list(struct pipe *head, int indent);
1899
1900/* return code is the exit status of the pipe */
1901static int free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001902{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001903 char **p;
1904 struct command *command;
1905 struct redir_struct *r, *rnext;
1906 int a, i, ret_code = 0;
1907
1908 if (pi->stopped_cmds > 0)
1909 return ret_code;
1910 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1911 for (i = 0; i < pi->num_cmds; i++) {
1912 command = &pi->cmds[i];
1913 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1914 if (command->argv) {
1915 for (a = 0, p = command->argv; *p; a++, p++) {
1916 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1917 }
1918 free_strings(command->argv);
1919 command->argv = NULL;
1920 } else if (command->group) {
1921 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1922 ret_code = free_pipe_list(command->group, indent+3);
1923 debug_printf_clean("%s end group\n", indenter(indent));
1924 } else {
1925 debug_printf_clean("%s (nil)\n", indenter(indent));
1926 }
1927 for (r = command->redirects; r; r = rnext) {
1928 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1929 if (r->dup == -1) {
1930 /* guard against the case >$FOO, where foo is unset or blank */
1931 if (r->rd_filename) {
1932 debug_printf_clean(" %s\n", r->rd_filename);
1933 free(r->rd_filename);
1934 r->rd_filename = NULL;
1935 }
1936 } else {
1937 debug_printf_clean("&%d\n", r->dup);
1938 }
1939 rnext = r->next;
1940 free(r);
1941 }
1942 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001943 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001944 free(pi->cmds); /* children are an array, they get freed all at once */
1945 pi->cmds = NULL;
1946#if ENABLE_HUSH_JOB
1947 free(pi->cmdtext);
1948 pi->cmdtext = NULL;
1949#endif
1950 return ret_code;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001951}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001952
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001953static int free_pipe_list(struct pipe *head, int indent)
1954{
1955 int rcode = 0; /* if list has no members */
1956 struct pipe *pi, *next;
1957
1958 for (pi = head; pi; pi = next) {
1959#if HAS_KEYWORDS
1960 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1961#endif
1962 rcode = free_pipe(pi, indent);
1963 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1964 next = pi->next;
1965 /*pi->next = NULL;*/
1966 free(pi);
1967 }
1968 return rcode;
1969}
1970
1971
1972#if !BB_MMU
1973typedef struct nommu_save_t {
1974 char **new_env;
1975 char **old_env;
1976 char **argv;
1977} nommu_save_t;
1978#else
1979#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1980 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1981#define pseudo_exec(nommu_save, command, argv_expanded) \
1982 pseudo_exec(command, argv_expanded)
1983#endif
1984
Denis Vlasenko05743d72008-02-10 12:10:08 +00001985/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001986 * Never returns.
1987 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001988 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001989 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001990static 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 +00001991static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001992{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001993 int rcode;
1994 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001995 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001996
Denis Vlasenko1359da62007-04-21 23:27:30 +00001997 /* If a variable is assigned in a forest, and nobody listens,
1998 * was it ever really set?
1999 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002000 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002001 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002002
Denis Vlasenko9504e442008-10-29 01:19:15 +00002003 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002004#if BB_MMU
2005 putenv_all(new_env);
2006 free(new_env); /* optional */
2007#else
2008 nommu_save->new_env = new_env;
2009 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002010#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002011 if (argv_expanded) {
2012 argv = argv_expanded;
2013 } else {
2014 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002015#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002016 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002017#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002018 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002019
Denis Vlasenko1359da62007-04-21 23:27:30 +00002020 /*
2021 * Check if the command matches any of the builtins.
2022 * Depending on context, this might be redundant. But it's
2023 * easier to waste a few CPU cycles than it is to figure out
2024 * if this is one of those cases.
2025 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002026 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00002027 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002028 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002029 rcode = x->function(argv);
2030 fflush(stdout);
2031 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00002032 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002033 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002034
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002035 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002036#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002037 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002038 int a = find_applet_by_name(argv[0]);
2039 if (a >= 0) {
2040 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002041 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002042// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2043 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002044 }
2045 /* re-exec ourselves with the new arguments */
2046 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00002047 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002048 /* If they called chroot or otherwise made the binary no longer
2049 * executable, fall through */
2050 }
2051 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002052#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002053
2054 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002055 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002056 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002057 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002058}
2059
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002060static int run_list(struct pipe *pi);
2061
Denis Vlasenko05743d72008-02-10 12:10:08 +00002062/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00002063 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002064static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002065static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002066{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002067 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002068 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002069
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002070 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00002071#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002072 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00002073#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00002074 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002075 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002076 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002077 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002078 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002079 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002080#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002081 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002082
2083 /* Can happen. See what bash does with ">foo" by itself. */
2084 debug_printf("trying to pseudo_exec null command\n");
2085 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002086}
2087
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002088#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002089static const char *get_cmdtext(struct pipe *pi)
2090{
2091 char **argv;
2092 char *p;
2093 int len;
2094
2095 /* This is subtle. ->cmdtext is created only on first backgrounding.
2096 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002097 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002098 if (pi->cmdtext)
2099 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002100 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002101 if (!argv || !argv[0]) {
2102 pi->cmdtext = xzalloc(1);
2103 return pi->cmdtext;
2104 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002105
2106 len = 0;
2107 do len += strlen(*argv) + 1; while (*++argv);
2108 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002109 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002110 do {
2111 len = strlen(*argv);
2112 memcpy(p, *argv, len);
2113 p += len;
2114 *p++ = ' ';
2115 } while (*++argv);
2116 p[-1] = '\0';
2117 return pi->cmdtext;
2118}
2119
Eric Andersenbafd94f2001-05-02 16:11:59 +00002120static void insert_bg_job(struct pipe *pi)
2121{
2122 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002123 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002124
2125 /* Linear search for the ID of the job to use */
2126 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002127 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002128 if (thejob->jobid >= pi->jobid)
2129 pi->jobid = thejob->jobid + 1;
2130
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002131 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002132 if (!G.job_list) {
2133 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002134 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002135 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002136 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002137 thejob->next = xmalloc(sizeof(*thejob));
2138 thejob = thejob->next;
2139 }
2140
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002141 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002142 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002143 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2144 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2145 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002146// TODO: do we really need to have so many fields which are just dead weight
2147// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002148 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002149 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002150 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002151 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002152 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002153
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002154 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002155 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002156 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2157 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002158 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002159}
2160
Eric Andersenbafd94f2001-05-02 16:11:59 +00002161static void remove_bg_job(struct pipe *pi)
2162{
2163 struct pipe *prev_pipe;
2164
Denis Vlasenko87a86552008-07-29 19:43:10 +00002165 if (pi == G.job_list) {
2166 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002167 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002168 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002169 while (prev_pipe->next != pi)
2170 prev_pipe = prev_pipe->next;
2171 prev_pipe->next = pi->next;
2172 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002173 if (G.job_list)
2174 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002175 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002176 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002177}
Eric Andersen028b65b2001-06-28 01:10:11 +00002178
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002179/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002180static void delete_finished_bg_job(struct pipe *pi)
2181{
2182 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002183 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002184 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002185 free(pi);
2186}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002187#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002188
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002189/* Check to see if any processes have exited -- if they
2190 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002191static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002192{
Eric Andersenc798b072001-06-22 06:23:03 +00002193 int attributes;
2194 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002195#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002196 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002197#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002198 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002199 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002200
Eric Andersenc798b072001-06-22 06:23:03 +00002201 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002202 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002203 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002204
Denis Vlasenko1359da62007-04-21 23:27:30 +00002205/* Do we do this right?
2206 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002207 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002208 * [3]+ Stopped sleep 20 | false
2209 * bash-3.00# echo $?
2210 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2211 */
2212
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002213//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2214//are stopped. Testcase: "cat | cat" in a script (not on command line)
2215// + killall -STOP cat
2216
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002217 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00002218// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00002219 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002220 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002221 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002222#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002223 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002224 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002225 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2226 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002227 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002228 childpid, WTERMSIG(status), WEXITSTATUS(status));
2229 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002230 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002231 childpid, WEXITSTATUS(status));
2232#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002233 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002234 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002235 for (i = 0; i < fg_pipe->num_cmds; i++) {
2236 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2237 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002238 continue;
2239 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2240 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002241 fg_pipe->cmds[i].pid = 0;
2242 fg_pipe->alive_cmds--;
2243 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002244 /* last process gives overall exitstatus */
2245 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002246 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002247 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002248 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002249 fg_pipe->cmds[i].is_stopped = 1;
2250 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002251 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002252 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2253 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2254 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002255 /* All processes in fg pipe have exited/stopped */
2256#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002257 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002258 insert_bg_job(fg_pipe);
2259#endif
2260 return rcode;
2261 }
2262 /* There are still running processes in the fg pipe */
2263 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002264 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002265 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002266 }
2267
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002268#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002269 /* We asked to wait for bg or orphaned children */
2270 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002271 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002272 for (i = 0; i < pi->num_cmds; i++) {
2273 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002274 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002275 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002276 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002277 /* Happens when shell is used as init process (init=/bin/sh) */
2278 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002279 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002280
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002281 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002282 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002283 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002284 pi->cmds[i].pid = 0;
2285 pi->alive_cmds--;
2286 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002287 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002288 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002289 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002290 }
2291 } else {
2292 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002293 pi->cmds[i].is_stopped = 1;
2294 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002295 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002296#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002297 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002298
Denis Vlasenko1359da62007-04-21 23:27:30 +00002299 /* wait found no children or failed */
2300
2301 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002302 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002303 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002304}
2305
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002306#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002307static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2308{
2309 pid_t p;
2310 int rcode = checkjobs(fg_pipe);
2311 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002312 p = getpgid(0); /* pgid of our process */
2313 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002314 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002315 return rcode;
2316}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002317#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002318
Denis Vlasenko05743d72008-02-10 12:10:08 +00002319/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00002320 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002321 *
2322 * return code is normally -1, when the caller has to wait for children
2323 * to finish to determine the exit status of the pipe. If the pipe
2324 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002325 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002326 * return value.
2327 *
2328 * The input of the pipe is always stdin, the output is always
2329 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2330 * because it tries to avoid running the command substitution in
2331 * subshell, when that is in fact necessary. The subshell process
2332 * now has its stdout directed to the input of the appropriate pipe,
2333 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00002334 *
2335 * Returns -1 only if started some children. IOW: we have to
2336 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00002337 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002338static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002339{
2340 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002341 int nextin;
2342 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002343 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002344 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002345 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00002346 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002347 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002348 /* it is not always needed, but we aim to smaller code */
2349 int squirrel[] = { -1, -1, -1 };
2350 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002351 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00002352
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002353 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002354
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002355#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00002356 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002357#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002358 pi->alive_cmds = 1;
2359 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002360
2361 /* Check if this is a simple builtin (not part of a pipe).
2362 * Builtins within pipes have to fork anyway, and are handled in
2363 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2364 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002365 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002366
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002367#if ENABLE_HUSH_FUNCTIONS
2368 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2369 /* We "execute" function definition */
2370 bb_error_msg("here we ought to remember function definition, and go on");
2371 return EXIT_SUCCESS;
2372 }
2373#endif
2374
2375 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00002376 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002377 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002378 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002379 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00002380 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002381 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002382 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00002383 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002384 }
2385
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002386 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002387 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002388
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002389 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002390 char **new_env = NULL;
2391 char **old_env = NULL;
2392
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002393 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002394 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002395 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002396 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002397 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002398 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002399 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00002400 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002401 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00002402 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002403
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002404 /* Expand the rest into (possibly) many strings each */
2405 argv_expanded = expand_strvec_to_strvec(argv + i);
2406
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002407 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002408 if (strcmp(argv_expanded[0], x->cmd) != 0)
2409 continue;
2410 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2411 debug_printf("exec with redirects only\n");
2412 setup_redirects(command, NULL);
2413 rcode = EXIT_SUCCESS;
2414 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00002415 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002416 debug_printf("builtin inline %s\n", argv_expanded[0]);
2417 /* XXX setup_redirects acts on file descriptors, not FILEs.
2418 * This is perfect for work that comes after exec().
2419 * Is it really safe for inline use? Experimentally,
2420 * things seem to work with glibc. */
2421 setup_redirects(command, squirrel);
2422 new_env = expand_assignments(argv, command->assignment_cnt);
2423 old_env = putenv_all_and_save_old(new_env);
2424 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2425 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002426#if ENABLE_FEATURE_SH_STANDALONE
2427 clean_up_and_ret:
2428#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002429 restore_redirects(squirrel);
2430 free_strings_and_unsetenv(new_env, 1);
2431 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002432 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002433 clean_up_and_ret1:
2434 free(argv_expanded);
2435 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2436 debug_printf_exec("run_pipe return %d\n", rcode);
2437 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002438 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002439#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002440 i = find_applet_by_name(argv_expanded[0]);
2441 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2442 setup_redirects(command, squirrel);
2443 save_nofork_data(&G.nofork_save);
2444 new_env = expand_assignments(argv, command->assignment_cnt);
2445 old_env = putenv_all_and_save_old(new_env);
2446 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2447 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2448 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002449 }
2450#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002451 }
2452
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002453 /* NB: argv_expanded may already be created, and that
2454 * might include `cmd` runs! Do not rerun it! We *must*
2455 * use argv_expanded if it's non-NULL */
2456
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002457 /* Disable job control signals for shell (parent) and
2458 * for initial child code after fork */
2459 set_jobctrl_sighandler(SIG_IGN);
2460
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002461 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002462 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002463 nextin = 0;
2464
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002465 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00002466#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002467 volatile nommu_save_t nommu_save;
2468 nommu_save.new_env = NULL;
2469 nommu_save.old_env = NULL;
2470 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002471#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002472 command = &(pi->cmds[i]);
2473 if (command->argv) {
2474 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002475 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002476 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002477
2478 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002479 pipefds[0] = 0;
2480 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002481 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002482 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00002483
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002484 command->pid = BB_MMU ? fork() : vfork();
2485 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00002486 if (ENABLE_HUSH_JOB)
2487 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002488#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002489 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00002490 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002491 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002492 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002493 /* Don't do pgrp restore anymore on fatal signals */
2494 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002495 pgrp = pi->pgrp;
2496 if (pgrp < 0) /* true for 1st process only */
2497 pgrp = getpid();
2498 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002499 /* We do it in *every* child, not just first,
2500 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002501 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002502 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002503 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002504#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00002505 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002506 xmove_fd(pipefds[1], 1); /* write end */
2507 if (pipefds[0] > 1)
2508 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00002509 /* Like bash, explicit redirects override pipes,
2510 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002511 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00002512
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002513 /* Restore default handlers just prior to exec */
2514 set_jobctrl_sighandler(SIG_DFL);
2515 set_misc_sighandler(SIG_DFL);
2516 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002517 /* Stores to nommu_save list of env vars putenv'ed
2518 * (NOMMU, on MMU we don't need that) */
2519 /* cast away volatility... */
2520 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002521 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002522 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002523 /* parent */
2524#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002525 /* Clean up after vforked child */
2526 free(nommu_save.argv);
2527 free_strings_and_unsetenv(nommu_save.new_env, 1);
2528 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002529#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002530 free(argv_expanded);
2531 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002532 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002533 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002534 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002535 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002536 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002537#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002538 /* Second and next children need to know pid of first one */
2539 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002540 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002541#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002542 }
Eric Andersen25f27032001-04-26 23:22:31 +00002543
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002544 if (i)
2545 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002546 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002547 close(pipefds[1]); /* write end */
2548 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002549 nextin = pipefds[0];
2550 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002551
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002552 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002553 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2554 return 1;
2555 }
2556
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002557 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002558 return -1;
2559}
2560
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002561#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002562static void debug_print_tree(struct pipe *pi, int lvl)
2563{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002564 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002565 [PIPE_SEQ] = "SEQ",
2566 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002567 [PIPE_OR ] = "OR" ,
2568 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002569 };
2570 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002571 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002572#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002573 [RES_IF ] = "IF" ,
2574 [RES_THEN ] = "THEN" ,
2575 [RES_ELIF ] = "ELIF" ,
2576 [RES_ELSE ] = "ELSE" ,
2577 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002578#endif
2579#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002580 [RES_FOR ] = "FOR" ,
2581 [RES_WHILE] = "WHILE",
2582 [RES_UNTIL] = "UNTIL",
2583 [RES_DO ] = "DO" ,
2584 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002585#endif
2586#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002587 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002588#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002589#if ENABLE_HUSH_CASE
2590 [RES_CASE ] = "CASE" ,
2591 [RES_MATCH] = "MATCH",
2592 [RES_CASEI] = "CASEI",
2593 [RES_ESAC ] = "ESAC" ,
2594#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002595 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002596 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002597 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002598 static const char *const GRPTYPE[] = {
2599 "()",
2600 "{}",
2601#if ENABLE_HUSH_FUNCTIONS
2602 "func()",
2603#endif
2604 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002605
2606 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002607
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002608 pin = 0;
2609 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002610 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2611 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002612 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002613 while (prn < pi->num_cmds) {
2614 struct command *command = &pi->cmds[prn];
2615 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002616
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002617 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2618 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002619 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002620 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002621 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002622 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002623 prn++;
2624 continue;
2625 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002626 if (argv) while (*argv) {
2627 fprintf(stderr, " '%s'", *argv);
2628 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002629 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002630 fprintf(stderr, "\n");
2631 prn++;
2632 }
2633 pi = pi->next;
2634 pin++;
2635 }
2636}
2637#endif
2638
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002639/* NB: called by pseudo_exec, and therefore must not modify any
2640 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002641static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002642{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002643#if ENABLE_HUSH_CASE
2644 char *case_word = NULL;
2645#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002646#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002647 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002648 char *for_varname = NULL;
2649 char **for_lcur = NULL;
2650 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002651#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002652 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002653 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002654#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002655 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002656#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002657 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002658#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002659 /*enum reserved_style*/ smallint rword = RES_NONE;
2660 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002661
Denis Vlasenko87a86552008-07-29 19:43:10 +00002662 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002663
Denis Vlasenko06810332007-05-21 23:30:54 +00002664#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002665 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002666 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2667 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002668 continue;
2669 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002670 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002671 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002672 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002673 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002674 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002675 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002676 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002677 continue;
2678 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002679 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2680 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002681 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002682 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002683 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002684 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002685 }
2686 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002687#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002688
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002689 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002690 * in order to return, no direct "return" statements please.
2691 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002692
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002693#if ENABLE_HUSH_JOB
2694 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2695 * We are saving state before entering outermost list ("while...done")
2696 * so that ctrl-Z will correctly background _entire_ outermost list,
2697 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002698 if (++G.run_list_level == 1 && G.interactive_fd) {
2699 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002700 /* ctrl-Z forked and we are parent; or ctrl-C.
2701 * Sighandler has longjmped us here */
2702 signal(SIGINT, SIG_IGN);
2703 signal(SIGTSTP, SIG_IGN);
2704 /* Restore level (we can be coming from deep inside
2705 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002706 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002707#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002708 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002709 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002710 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002711 }
2712#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002713 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002714 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2715 * Remember this child as background job */
2716 insert_bg_job(pi);
2717 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002718 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002719 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002720 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002721 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002722 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002723 rcode = 0;
2724 goto ret;
2725 }
2726 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002727 G.toplevel_list = pi;
2728 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002729#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002730 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002731#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002732 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002733 signal(SIGINT, handler_ctrl_c);
2734 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002735#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002736
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002737 /* Go through list of pipes, (maybe) executing them. */
2738 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002739 IF_HAS_KEYWORDS(rword = pi->res_word;)
2740 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002741 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2742 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002743#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002744 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002745 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002746 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002747 /* start of a loop: remember where loop starts */
2748 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002749 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002750 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002751#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002752 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002753 if (pi->followup == PIPE_SEQ)
2754 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002755 /* it is "<false> && CMD" or "<true> || CMD"
2756 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002757 continue;
2758 }
2759 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002760 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002761#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002762 if (cond_code) {
2763 if (rword == RES_THEN) {
2764 /* "if <false> THEN cmd": skip cmd */
2765 continue;
2766 }
2767 } else {
2768 if (rword == RES_ELSE || rword == RES_ELIF) {
2769 /* "if <true> then ... ELSE/ELIF cmd":
2770 * skip cmd and all following ones */
2771 break;
2772 }
2773 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002774#endif
2775#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002776 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002777 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002778 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002779
2780 static const char encoded_dollar_at[] ALIGN1 = {
2781 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2782 }; /* encoded representation of "$@" */
2783 static const char *const encoded_dollar_at_argv[] = {
2784 encoded_dollar_at, NULL
2785 }; /* argv list with one element: "$@" */
2786 char **vals;
2787
2788 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002789 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002790 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002791 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002792 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002793 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002794 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002795 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002796 debug_print_strings("for_list made from", vals);
2797 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002798 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002799 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002800 for_varname = pi->cmds[0].argv[0];
2801 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002802 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002803 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002804 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002805 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002806 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002807 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002808 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002809 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002810 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002811 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002812 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002813//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002814 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2815 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002816 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002817 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002818 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002819 if (rword == RES_DONE) {
2820 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002821 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002822#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002823#if ENABLE_HUSH_CASE
2824 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002825 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002826 continue;
2827 }
2828 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002829 char **argv;
2830
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002831 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2832 break;
2833 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002834 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002835 while (*argv) {
2836 char *pattern = expand_string_to_string(*argv);
2837 /* TODO: which FNM_xxx flags to use? */
2838 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2839 free(pattern);
2840 if (cond_code == 0) { /* match! we will execute this branch */
2841 free(case_word); /* make future "word)" stop */
2842 case_word = NULL;
2843 break;
2844 }
2845 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002846 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002847 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002848 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002849 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002850 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002851 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002852 }
2853#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002854 if (pi->num_cmds == 0)
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00002855 goto check_jobs_and_continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002856
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002857 /* After analyzing all keywords and conditions, we decided
2858 * to execute this pipe. NB: has to do checkjobs(NULL)
2859 * after run_pipe() to collect any background children,
2860 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002861 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002862 {
2863 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002864#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002865 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002866#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002867 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2868 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002869 /* we only ran a builtin: rcode is already known
2870 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002871#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002872 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002873 if (G.flag_break_continue) {
2874 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002875 /* we might fall into outer *loop*,
2876 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002877 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002878 G.depth_break_continue--;
2879 if (G.depth_break_continue == 0)
2880 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002881 /* else: e.g. "continue 2" should *break* once, *then* continue */
2882 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002883 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002884 goto check_jobs_and_break;
2885 /* "continue": simulate end of loop */
2886 rword = RES_DONE;
2887 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002888 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002889#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002890 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002891 /* what does bash do with attempts to background builtins? */
2892 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002893 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2894 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002895#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002896 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002897 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002898#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002899 rcode = 0; /* EXIT_SUCCESS */
2900 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002901#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002902 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002903 /* waits for completion, then fg's main shell */
2904 rcode = checkjobs_and_fg_shell(pi);
2905 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2906 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002907#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002908 { /* this one just waits for completion */
2909 rcode = checkjobs(pi);
2910 debug_printf_exec(": checkjobs returned %d\n", rcode);
2911 }
Eric Andersen25f27032001-04-26 23:22:31 +00002912 }
2913 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002914 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002915 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002916
2917 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002918#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002919 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002920 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002921#endif
2922#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002923 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002924 if (rcode) {
2925 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002926 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002927 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002928 }
2929 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002930 if (!rcode) {
2931 check_jobs_and_break:
2932 checkjobs(NULL);
2933 break;
2934 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002935 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002936#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002937 if ((rcode == 0 && pi->followup == PIPE_OR)
2938 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002939 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002940 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002941 }
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00002942
2943 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00002944 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002945 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002946
2947#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002948 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002949 /* ctrl-Z forked somewhere in the past, we are the child,
2950 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002951//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002952 exit(rcode);
2953 }
2954 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002955 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002956 signal(SIGTSTP, SIG_IGN);
2957 signal(SIGINT, SIG_IGN);
2958 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002959#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002960 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002961#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002962 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002963 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002964 free(for_list);
2965#endif
2966#if ENABLE_HUSH_CASE
2967 free(case_word);
2968#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002969 return rcode;
2970}
2971
Eric Andersen25f27032001-04-26 23:22:31 +00002972/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002973static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002974{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002975 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002976 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002977 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002978 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002979 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002980 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002981 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002982 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002983 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002984 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002985 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002986 return rcode;
2987}
2988
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002989
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002990/* Peek ahead in the in_str to find out if we have a "&n" construct,
2991 * as in "2>&1", that represents duplicating a file descriptor.
2992 * Return either -2 (syntax error), -1 (no &), or the number found.
2993 */
2994static int redirect_dup_num(struct in_str *input)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002995{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002996 int ch, d = 0, ok = 0;
2997 ch = i_peek(input);
2998 if (ch != '&') return -1;
2999
3000 i_getch(input); /* get the & */
3001 ch = i_peek(input);
3002 if (ch == '-') {
3003 i_getch(input);
3004 return -3; /* "-" represents "close me" */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003005 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003006 while (isdigit(ch)) {
3007 d = d*10 + (ch-'0');
3008 ok = 1;
3009 i_getch(input);
3010 ch = i_peek(input);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003011 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003012 if (ok) return d;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003013
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003014 bb_error_msg("ambiguous redirect");
3015 return -2;
Eric Andersen78a7c992001-05-15 16:30:25 +00003016}
3017
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003018/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00003019 * for file descriptor duplication, e.g., "2>&1".
3020 * Return code is 0 normally, 1 if a syntax error is detected in src.
3021 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003022static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00003023 struct in_str *input)
3024{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003025 struct command *command = ctx->command;
3026 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003027 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003028
3029 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003030 while (redir) {
3031 last_redir = redir;
3032 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00003033 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003034 redir = xzalloc(sizeof(struct redir_struct));
3035 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003036 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00003037 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003038 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003039 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003040 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00003041 }
3042
Denis Vlasenko55789c62008-06-18 16:30:42 +00003043 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003044 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00003045
3046 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3047
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003048 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00003049 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003050 if (redir->dup == -2)
3051 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00003052 if (redir->dup != -1) {
3053 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00003054 * is legit; I postpone that to "run time"
3055 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00003056 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3057 } else {
3058 /* We do _not_ try to open the file that src points to,
3059 * since we need to return and let src be expanded first.
3060 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00003061 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00003062 ctx->pending_redirect = redir;
3063 }
3064 return 0;
3065}
3066
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003067
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003068static struct pipe *new_pipe(void)
3069{
Eric Andersen25f27032001-04-26 23:22:31 +00003070 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003071 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003072 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003073 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003074 return pi;
3075}
3076
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003077/* Command (member of a pipe) is complete. The only possible error here
3078 * is out of memory, in which case xmalloc exits. */
3079static int done_command(struct parse_context *ctx)
3080{
3081 /* The command is really already in the pipe structure, so
3082 * advance the pipe counter and make a new, null command. */
3083 struct pipe *pi = ctx->pipe;
3084 struct command *command = ctx->command;
3085
3086 if (command) {
3087 if (command->group == NULL
3088 && command->argv == NULL
3089 && command->redirects == NULL
3090 ) {
3091 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3092 return pi->num_cmds;
3093 }
3094 pi->num_cmds++;
3095 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3096 } else {
3097 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3098 }
3099
3100 /* Only real trickiness here is that the uncommitted
3101 * command structure is not counted in pi->num_cmds. */
3102 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3103 command = &pi->cmds[pi->num_cmds];
3104 memset(command, 0, sizeof(*command));
3105
3106 ctx->command = command;
3107 /* but ctx->pipe and ctx->list_head remain unchanged */
3108
3109 return pi->num_cmds; /* used only for 0/nonzero check */
3110}
3111
3112static void done_pipe(struct parse_context *ctx, pipe_style type)
3113{
3114 int not_null;
3115
3116 debug_printf_parse("done_pipe entered, followup %d\n", type);
3117 /* Close previous command */
3118 not_null = done_command(ctx);
3119 ctx->pipe->followup = type;
3120 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3121 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3122 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3123
3124 /* Without this check, even just <enter> on command line generates
3125 * tree of three NOPs (!). Which is harmless but annoying.
3126 * IOW: it is safe to do it unconditionally.
3127 * RES_NONE case is for "for a in; do ..." (empty IN set)
3128 * to work, possibly other cases too. */
3129 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3130 struct pipe *new_p;
3131 debug_printf_parse("done_pipe: adding new pipe: "
3132 "not_null:%d ctx->ctx_res_w:%d\n",
3133 not_null, ctx->ctx_res_w);
3134 new_p = new_pipe();
3135 ctx->pipe->next = new_p;
3136 ctx->pipe = new_p;
3137 ctx->command = NULL; /* needed! */
3138 /* RES_THEN, RES_DO etc are "sticky" -
3139 * they remain set for commands inside if/while.
3140 * This is used to control execution.
3141 * RES_FOR and RES_IN are NOT sticky (needed to support
3142 * cases where variable or value happens to match a keyword):
3143 */
3144#if ENABLE_HUSH_LOOPS
3145 if (ctx->ctx_res_w == RES_FOR
3146 || ctx->ctx_res_w == RES_IN)
3147 ctx->ctx_res_w = RES_NONE;
3148#endif
3149#if ENABLE_HUSH_CASE
3150 if (ctx->ctx_res_w == RES_MATCH)
3151 ctx->ctx_res_w = RES_CASEI;
3152#endif
3153 /* Create the memory for command, roughly:
3154 * ctx->pipe->cmds = new struct command;
3155 * ctx->command = &ctx->pipe->cmds[0];
3156 */
3157 done_command(ctx);
3158 }
3159 debug_printf_parse("done_pipe return\n");
3160}
3161
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003162static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003163{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003164 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003165 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003166 /* Create the memory for command, roughly:
3167 * ctx->pipe->cmds = new struct command;
3168 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003169 */
3170 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003171}
3172
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003173
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003174/* If a reserved word is found and processed, parse context is modified
3175 * and 1 is returned.
3176 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003177 * case, function, and select are obnoxious, save those for later.
3178 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003179#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003180struct reserved_combo {
3181 char literal[6];
3182 unsigned char res;
3183 unsigned char assignment_flag;
3184 int flag;
3185};
3186enum {
3187 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003188#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003189 FLAG_IF = (1 << RES_IF ),
3190 FLAG_THEN = (1 << RES_THEN ),
3191 FLAG_ELIF = (1 << RES_ELIF ),
3192 FLAG_ELSE = (1 << RES_ELSE ),
3193 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003194#endif
3195#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003196 FLAG_FOR = (1 << RES_FOR ),
3197 FLAG_WHILE = (1 << RES_WHILE),
3198 FLAG_UNTIL = (1 << RES_UNTIL),
3199 FLAG_DO = (1 << RES_DO ),
3200 FLAG_DONE = (1 << RES_DONE ),
3201 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003202#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003203#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003204 FLAG_MATCH = (1 << RES_MATCH),
3205 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003206#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003207 FLAG_START = (1 << RES_XXXX ),
3208};
3209
3210static const struct reserved_combo* match_reserved_word(o_string *word)
3211{
Eric Andersen25f27032001-04-26 23:22:31 +00003212 /* Mostly a list of accepted follow-up reserved words.
3213 * FLAG_END means we are done with the sequence, and are ready
3214 * to turn the compound list into a command.
3215 * FLAG_START means the word must start a new compound list.
3216 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003217 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003218#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003219 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3220 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3221 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3222 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3223 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3224 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003225#endif
3226#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003227 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3228 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3229 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3230 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3231 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3232 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003233#endif
3234#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003235 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3236 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003237#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003238 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003239 const struct reserved_combo *r;
3240
3241 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3242 if (strcmp(word->data, r->literal) == 0)
3243 return r;
3244 }
3245 return NULL;
3246}
3247static int reserved_word(o_string *word, struct parse_context *ctx)
3248{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003249#if ENABLE_HUSH_CASE
3250 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003251 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003252 };
3253#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003254 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003255
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003256 r = match_reserved_word(word);
3257 if (!r)
3258 return 0;
3259
3260 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003261#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003262 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3263 /* "case word IN ..." - IN part starts first match part */
3264 r = &reserved_match;
3265 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003266#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003267 if (r->flag == 0) { /* '!' */
3268 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003269 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003270 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003271 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003272 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003273 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003274 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003275 if (r->flag & FLAG_START) {
3276 struct parse_context *new;
3277 debug_printf("push stack\n");
3278 new = xmalloc(sizeof(*new));
3279 *new = *ctx; /* physical copy */
3280 initialize_context(ctx);
3281 ctx->stack = new;
3282 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3283 syntax(NULL);
3284 ctx->ctx_res_w = RES_SNTX;
3285 return 1;
3286 }
3287 ctx->ctx_res_w = r->res;
3288 ctx->old_flag = r->flag;
3289 if (ctx->old_flag & FLAG_END) {
3290 struct parse_context *old;
3291 debug_printf("pop stack\n");
3292 done_pipe(ctx, PIPE_SEQ);
3293 old = ctx->stack;
3294 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003295 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003296 *ctx = *old; /* physical copy */
3297 free(old);
3298 }
3299 word->o_assignment = r->assignment_flag;
3300 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003301}
Denis Vlasenko06810332007-05-21 23:30:54 +00003302#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003303
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003304//TODO: many, many callers don't check error from done_word()
3305
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003306/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003307 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003308static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003309{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003310 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003311
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003312 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003313 if (word->length == 0 && word->nonnull == 0) {
3314 debug_printf_parse("done_word return 0: true null, ignored\n");
3315 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003316 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003317 /* If this word wasn't an assignment, next ones definitely
3318 * can't be assignments. Even if they look like ones. */
3319 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3320 && word->o_assignment != WORD_IS_KEYWORD
3321 ) {
3322 word->o_assignment = NOT_ASSIGNMENT;
3323 } else {
3324 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003325 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003326 word->o_assignment = MAYBE_ASSIGNMENT;
3327 }
3328
Eric Andersen25f27032001-04-26 23:22:31 +00003329 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003330 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3331 * only if run as "bash", not "sh" */
3332 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003333 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003334 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003335 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003336 /* "{ echo foo; } echo bar" - bad */
3337 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003338 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003339 syntax(NULL);
3340 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3341 return 1;
3342 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003343#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003344#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003345 if (ctx->ctx_dsemicolon
3346 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3347 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003348 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003349 /* ctx->ctx_res_w = RES_MATCH; */
3350 ctx->ctx_dsemicolon = 0;
3351 } else
3352#endif
3353
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003354 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003355#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003356 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3357 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003358#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003359 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003360 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3361 if (reserved_word(word, ctx)) {
3362 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003363 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3364 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003365 }
Eric Andersen25f27032001-04-26 23:22:31 +00003366 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003367#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003368 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003369 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3370 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003371 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003372 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003373 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003374 char *p = word->data;
3375 while (p[0] == SPECIAL_VAR_SYMBOL
3376 && (p[1] & 0x7f) == '@'
3377 && p[2] == SPECIAL_VAR_SYMBOL
3378 ) {
3379 p += 3;
3380 }
3381 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003382 /* saw no "$@", or not only "$@" but some
3383 * real text is there too */
3384 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003385 * e.g. "", $empty"" etc to not disappear */
3386 o_addchr(word, SPECIAL_VAR_SYMBOL);
3387 o_addchr(word, SPECIAL_VAR_SYMBOL);
3388 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003389 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003390 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003391 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003392 }
Eric Andersen25f27032001-04-26 23:22:31 +00003393
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003394 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003395 ctx->pending_redirect = NULL;
3396
Denis Vlasenko06810332007-05-21 23:30:54 +00003397#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003398 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003399 /* NB: basically, this makes hush see "for v in ..." syntax as if
3400 * as it is "for v; in ...". FOR and IN become two pipe structs
3401 * in parse tree. */
3402 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003403//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003404 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003405 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003406#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003407#if ENABLE_HUSH_CASE
3408 /* Force CASE to have just one word */
3409 if (ctx->ctx_res_w == RES_CASE) {
3410 done_pipe(ctx, PIPE_SEQ);
3411 }
3412#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003413 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003414 return 0;
3415}
3416
Eric Andersen25f27032001-04-26 23:22:31 +00003417/* If a redirect is immediately preceded by a number, that number is
3418 * supposed to tell which file descriptor to redirect. This routine
3419 * looks for such preceding numbers. In an ideal world this routine
3420 * needs to handle all the following classes of redirects...
3421 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3422 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3423 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3424 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3425 * A -1 output from this program means no valid number was found, so the
3426 * caller should use the appropriate default for this redirection.
3427 */
3428static int redirect_opt_num(o_string *o)
3429{
3430 int num;
3431
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003432 if (o->length == 0)
3433 return -1;
3434 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003435 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003436 return -1;
3437 }
3438 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003439 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003440 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003441 return num;
3442}
3443
Mike Frysingerddbee972009-03-22 22:48:41 +00003444static int parse_stream(o_string *dest, struct parse_context *ctx,
3445 struct in_str *input0, const char *end_trigger);
3446
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003447#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003448static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003449{
3450 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003451 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003452
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003453 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003454/* *** NOMMU WARNING *** */
3455/* By using vfork here, we suspend parent till child exits or execs.
3456 * If child will not do it before it fills the pipe, it can block forever
3457 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003458 * Try this script:
3459 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3460 * huge=`cat TESTFILE` # will block here forever
3461 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003462 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003463 pid = BB_MMU ? fork() : vfork();
3464 if (pid < 0)
3465 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003466 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003467 if (ENABLE_HUSH_JOB)
3468 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003469 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003470 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003471 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003472#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003473 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003474#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003475 /* Process substitution is not considered to be usual
3476 * 'command execution'.
3477 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3478 /* Not needed, we are relying on it being disabled
3479 * everywhere outside actual command execution. */
3480 /*set_jobctrl_sighandler(SIG_IGN);*/
3481 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003482 /* Freeing 'head' here would break NOMMU. */
3483 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003484 }
Eric Andersen25f27032001-04-26 23:22:31 +00003485 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003486 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003487 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003488 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003489}
3490
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003491/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003492static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003493 struct in_str *input,
3494 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003495{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003496 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003497 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003498 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003499 FILE *p;
3500 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003501
Eric Andersen25f27032001-04-26 23:22:31 +00003502 initialize_context(&inner);
3503
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003504 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003505 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003506 if (retcode != 0)
3507 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003508 done_word(&result, &inner);
3509 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003510 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003511
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003512 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003513 if (p == NULL)
3514 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003515 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003516 setup_file_in_str(&pipe_str, p);
3517
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003518 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003519 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003520 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003521 if (ch == '\n') {
3522 eol_cnt++;
3523 continue;
3524 }
3525 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003526 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003527 eol_cnt--;
3528 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003529 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003530 }
3531
3532 debug_printf("done reading from pipe, pclose()ing\n");
3533 /* This is the step that wait()s for the child. Should be pretty
3534 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003535 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003536 * at the same time. That would be a lot of work, and contrary
3537 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003538 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003539 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003540 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003541 return retcode;
3542}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003543#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003544
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003545static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003546 struct in_str *input, int ch)
3547{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003548 /* dest contains characters seen prior to ( or {.
3549 * Typically it's empty, but for functions defs,
3550 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003551 int rcode;
3552 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003553 struct parse_context sub;
3554 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003555
3556 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003557#if ENABLE_HUSH_FUNCTIONS
3558 if (ch == 'F') { /* function definition? */
3559 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3560 //command->fname = dest->data;
3561 command->grp_type = GRP_FUNCTION;
3562//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3563 memset(dest, 0, sizeof(*dest));
3564 }
3565#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003566 if (command->argv /* word [word](... */
3567 || dest->length /* word(... */
3568 || dest->nonnull /* ""(... */
3569 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003570 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003571 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3572 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003573 }
3574 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003575 endch = "}";
3576 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003577 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003578 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003579 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003580 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003581 if (rcode == 0) {
3582 done_word(dest, &sub); /* finish off the final word in the subcontext */
3583 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003584 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003585 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003586 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003587 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003588 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003589}
3590
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003591#if ENABLE_HUSH_TICK
3592/* Subroutines for copying $(...) and `...` things */
3593static void add_till_backquote(o_string *dest, struct in_str *input);
3594/* '...' */
3595static void add_till_single_quote(o_string *dest, struct in_str *input)
3596{
3597 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003598 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003599 if (ch == EOF)
3600 break;
3601 if (ch == '\'')
3602 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003603 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003604 }
3605}
3606/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3607static void add_till_double_quote(o_string *dest, struct in_str *input)
3608{
3609 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003610 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003611 if (ch == '"')
3612 break;
3613 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003614 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003615 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003616 }
3617 if (ch == EOF)
3618 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003619 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003620 if (ch == '`') {
3621 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003622 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003623 continue;
3624 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003625 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003626 }
3627}
3628/* Process `cmd` - copy contents until "`" is seen. Complicated by
3629 * \` quoting.
3630 * "Within the backquoted style of command substitution, backslash
3631 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3632 * The search for the matching backquote shall be satisfied by the first
3633 * backquote found without a preceding backslash; during this search,
3634 * if a non-escaped backquote is encountered within a shell comment,
3635 * a here-document, an embedded command substitution of the $(command)
3636 * form, or a quoted string, undefined results occur. A single-quoted
3637 * or double-quoted string that begins, but does not end, within the
3638 * "`...`" sequence produces undefined results."
3639 * Example Output
3640 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3641 */
3642static void add_till_backquote(o_string *dest, struct in_str *input)
3643{
3644 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003645 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003646 if (ch == '`')
3647 break;
3648 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003649 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003650 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003651 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003652 ch = ch2;
3653 }
3654 if (ch == EOF)
3655 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003656 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003657 }
3658}
3659/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3660 * quoting and nested ()s.
3661 * "With the $(command) style of command substitution, all characters
3662 * following the open parenthesis to the matching closing parenthesis
3663 * constitute the command. Any valid shell script can be used for command,
3664 * except a script consisting solely of redirections which produces
3665 * unspecified results."
3666 * Example Output
3667 * echo $(echo '(TEST)' BEST) (TEST) BEST
3668 * echo $(echo 'TEST)' BEST) TEST) BEST
3669 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3670 */
3671static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3672{
3673 int count = 0;
3674 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003675 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003676 if (ch == EOF)
3677 break;
3678 if (ch == '(')
3679 count++;
3680 if (ch == ')')
3681 if (--count < 0)
3682 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003683 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003684 if (ch == '\'') {
3685 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003686 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003687 continue;
3688 }
3689 if (ch == '"') {
3690 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003691 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003692 continue;
3693 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003694 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3695 ch = i_getch(input);
3696 if (ch == EOF)
3697 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003698 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003699 continue;
3700 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003701 }
3702}
3703#endif /* ENABLE_HUSH_TICK */
3704
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003705/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003706static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003707{
Mike Frysinger6379bb42009-03-28 18:55:03 +00003708 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003709 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003710 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003711
3712 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003713 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003714 i_getch(input);
3715 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003716 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003717 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003718 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003719 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003720 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003721 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003722 if (!isalnum(ch) && ch != '_')
3723 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003724 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003725 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003727 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003728 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003729 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003730 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003731 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003732 o_addchr(dest, ch | quote_mask);
3733 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003734 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003735 case '$': /* pid */
3736 case '!': /* last bg pid */
3737 case '?': /* last exit code */
3738 case '#': /* number of args */
3739 case '*': /* args */
3740 case '@': /* args */
3741 goto make_one_char_var;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003742 case '{': {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003743 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003744
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003745 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3746 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003747 /* XXX maybe someone will try to escape the '}' */
Mike Frysinger6379bb42009-03-28 18:55:03 +00003748 expansion = 0;
3749 first_char = true;
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003750 all_digits = false;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003751 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003752 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003753 if (ch == '}')
3754 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003755
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003756 if (first_char) {
3757 if (ch == '#')
3758 /* ${#var}: length of var contents */
3759 goto char_ok;
3760 else if (isdigit(ch)) {
3761 all_digits = true;
3762 goto char_ok;
3763 }
3764 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00003765
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003766 if (expansion < 2 &&
3767 ((all_digits && !isdigit(ch)) ||
3768 (!all_digits && !isalnum(ch) && ch != '_')))
3769 {
Mike Frysinger6379bb42009-03-28 18:55:03 +00003770 /* handle parameter expansions
3771 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3772 */
3773 if (first_char)
3774 goto case_default;
3775 switch (ch) {
3776 case ':': /* null modifier */
3777 if (expansion == 0) {
3778 debug_printf_parse(": null modifier\n");
3779 ++expansion;
3780 break;
3781 }
3782 goto case_default;
3783
3784#if 0 /* not implemented yet :( */
3785 case '#': /* remove prefix */
3786 case '%': /* remove suffix */
3787 if (expansion == 0) {
3788 debug_printf_parse(": remove suffix/prefix\n");
3789 expansion = 2;
3790 break;
3791 }
3792 goto case_default;
3793#endif
3794
3795 case '-': /* default value */
3796 case '=': /* assign default */
3797 case '+': /* alternative */
3798 case '?': /* error indicate */
3799 debug_printf_parse(": parameter expansion\n");
3800 expansion = 2;
3801 break;
3802
3803 default:
3804 case_default:
3805 syntax("unterminated ${name}");
3806 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3807 return 1;
3808 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003809 }
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00003810
3811 char_ok:
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003812 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003813 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003814 quote_mask = 0;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003815 first_char = false;
Eric Andersen25f27032001-04-26 23:22:31 +00003816 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003817 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003818 break;
Mike Frysinger6379bb42009-03-28 18:55:03 +00003819 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003820#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003821 case '(': {
3822 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003823 i_getch(input);
3824 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3825 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003826 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003827 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003828 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003829 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003830 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003831#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003832 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003833 i_getch(input);
3834 ch = i_peek(input);
3835 if (isalnum(ch)) { /* it's $_name or $_123 */
3836 ch = '_';
3837 goto make_var;
3838 }
3839 /* else: it's $_ */
3840 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003841 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003842 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003843 return 1;
3844 break;
3845 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003846 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003847 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003848 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003849 return 0;
3850}
3851
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003852/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003853 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3854 * Return code is 0 if end_trigger char is met,
3855 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003856 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003857static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003858 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003859{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003860 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003861 int redir_fd;
3862 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003863 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003864 int next;
3865
Denis Vlasenkoff097622007-10-01 10:00:45 +00003866 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003867 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003868 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003869
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003870 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 +00003871
Denis Vlasenko1a735862007-05-23 00:32:25 +00003872 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003873 m = CHAR_IFS;
3874 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003875 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003876 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003877 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003878 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003879 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003880 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003881 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003882 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003883 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003884 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003885 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003886 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003887 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003888 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003889 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3890 return 1;
3891 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003892 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003893 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3894 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003895 && ch == '='
3896 && is_assignment(dest->data)
3897 ) {
3898 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3899 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003900 continue;
3901 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003902 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003903 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003904 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003905 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003906 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003907 if (ch == EOF)
3908 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003909 /* If we aren't performing a substitution, treat
3910 * a newline as a command separator.
3911 * [why we don't handle it exactly like ';'? --vda] */
3912 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003913#if ENABLE_HUSH_CASE
3914 /* "case ... in <newline> word) ..." -
3915 * newlines are ignored (but ';' wouldn't be) */
3916 if (dest->length == 0 // && argv[0] == NULL
3917 && ctx->ctx_res_w == RES_MATCH
3918 ) {
3919 continue;
3920 }
3921#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003922 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003923 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003924 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003925 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003926 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003927 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003928 /* Special case: (...word) makes last word terminate,
3929 * as if ';' is seen */
3930 if (ch == ')') {
3931 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003932//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003933 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003934 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003935 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003936 if (!HAS_KEYWORDS
3937 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3938 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003939 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3940 return 0;
3941 }
3942 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003943 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003944 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003945 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003946
3947 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3948 /* ch is a special char and thus this word
3949 * cannot be an assignment: */
3950 dest->o_assignment = NOT_ASSIGNMENT;
3951 }
3952
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003953 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003954 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003955 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003956 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003957 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003958 if (ch == EOF || ch == '\n')
3959 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003960 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003961 }
Eric Andersen25f27032001-04-26 23:22:31 +00003962 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003963 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003964 }
3965 break;
3966 case '\\':
3967 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003968 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003969 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003970 return 1;
3971 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003972 /* bash:
3973 * "The backslash retains its special meaning [in "..."]
3974 * only when followed by one of the following characters:
3975 * $, `, ", \, or <newline>. A double quote may be quoted
3976 * within double quotes by preceding it with a backslash.
3977 * If enabled, history expansion will be performed unless
3978 * an ! appearing in double quotes is escaped using
3979 * a backslash. The backslash preceding the ! is not removed."
3980 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003981 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003982 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003983 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003984 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003985 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003986 }
3987 } else {
3988 o_addchr(dest, '\\');
3989 o_addchr(dest, i_getch(input));
3990 }
Eric Andersen25f27032001-04-26 23:22:31 +00003991 break;
3992 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003993 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003994 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3995 return 1;
3996 }
Eric Andersen25f27032001-04-26 23:22:31 +00003997 break;
3998 case '\'':
3999 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004000 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004001 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004002 if (ch == EOF) {
4003 syntax("unterminated '");
4004 debug_printf_parse("parse_stream return 1: unterminated '\n");
4005 return 1;
4006 }
4007 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00004008 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004009 if (dest->o_assignment == NOT_ASSIGNMENT)
4010 o_addqchr(dest, ch);
4011 else
4012 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004013 }
Eric Andersen25f27032001-04-26 23:22:31 +00004014 break;
4015 case '"':
4016 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004017 shadow_quote ^= 1; /* invert */
4018 if (dest->o_assignment == NOT_ASSIGNMENT)
4019 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004020 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004021#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004022 case '`': {
4023 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004024 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00004025 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004026 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004027 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00004028 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00004029 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004030 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004031#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004032 case '>':
4033 redir_fd = redirect_opt_num(dest);
4034 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004035 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00004036 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004037 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004038 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004039 }
4040#if 0
4041 else if (next == '(') {
4042 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004043 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004044 return 1;
4045 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004046#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004047 setup_redirect(ctx, redir_fd, redir_style, input);
4048 break;
4049 case '<':
4050 redir_fd = redirect_opt_num(dest);
4051 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004052 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00004053 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004054 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004055 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004056 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004057 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004058 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004059 }
4060#if 0
4061 else if (next == '(') {
4062 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004063 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004064 return 1;
4065 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004066#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004067 setup_redirect(ctx, redir_fd, redir_style, input);
4068 break;
4069 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004070#if ENABLE_HUSH_CASE
4071 case_semi:
4072#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004073 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004074 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004075#if ENABLE_HUSH_CASE
4076 /* Eat multiple semicolons, detect
4077 * whether it means something special */
4078 while (1) {
4079 ch = i_peek(input);
4080 if (ch != ';')
4081 break;
4082 i_getch(input);
4083 if (ctx->ctx_res_w == RES_CASEI) {
4084 ctx->ctx_dsemicolon = 1;
4085 ctx->ctx_res_w = RES_MATCH;
4086 break;
4087 }
4088 }
4089#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004090 new_cmd:
4091 /* We just finished a cmd. New one may start
4092 * with an assignment */
4093 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00004094 break;
4095 case '&':
4096 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004097 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004098 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004099 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00004100 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004101 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004102 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004103 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004104 case '|':
4105 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004106#if ENABLE_HUSH_CASE
4107 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004108 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004109#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004110 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004111 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004112 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004113 } else {
4114 /* we could pick up a file descriptor choice here
4115 * with redirect_opt_num(), but bash doesn't do it.
4116 * "echo foo 2| cat" yields "foo 2". */
4117 done_command(ctx);
4118 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004119 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004120 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004121#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004122 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004123 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004124 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004125 && dest->length == 0 /* not word(... */
4126 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004127 ) {
4128 continue;
4129 }
4130#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004131#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004132 if (dest->length != 0 /* not just () but word() */
4133 && dest->nonnull == 0 /* not a"b"c() */
4134 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004135//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004136 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004137 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004138 ) {
4139 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004140 i_getch(input);
4141 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004142//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004143 ch = i_getch(input);
4144 } while (ch == ' ' || ch == '\n');
4145 if (ch != '{') {
4146 syntax("was expecting {");
4147 debug_printf_parse("parse_stream return 1\n");
4148 return 1;
4149 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004150 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004151 }
4152#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004153 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004154 if (parse_group(dest, ctx, input, ch) != 0) {
4155 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004156 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004157 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004158 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004159 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004160#if ENABLE_HUSH_CASE
4161 if (ctx->ctx_res_w == RES_MATCH)
4162 goto case_semi;
4163#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004164 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004165 /* proper use of this character is caught by end_trigger:
4166 * if we see {, we call parse_group(..., end_trigger='}')
4167 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004168 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004169 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004170 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004171 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004172 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004173 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004174 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004175 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004176 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004177 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004178 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004179 return 0;
4180}
4181
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004182static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004183{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004184 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004185 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004186}
4187
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004188static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004189{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004190 G.ifs = getenv("IFS");
4191 if (G.ifs == NULL)
4192 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004193 /* Precompute a list of 'flow through' behavior so it can be treated
4194 * quickly up front. Computation is necessary because of IFS.
4195 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004196 * The charmap[] array only really needs two bits each,
4197 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004198 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004199 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004200#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004201 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004202#else
4203 set_in_charmap("\\$\"", CHAR_SPECIAL);
4204#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004205 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004206 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004207}
4208
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004209/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004210 * from builtin_source() and builtin_eval() */
4211static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004212{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004213 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004214 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004215 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004216
Eric Andersen25f27032001-04-26 23:22:31 +00004217 do {
4218 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004219 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004220#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004221 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004222#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004223 /* We will stop & execute after each ';' or '\n'.
4224 * Example: "sleep 9999; echo TEST" + ctrl-C:
4225 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004226 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004227 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004228#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004229 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004230 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004231 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004232#endif
4233 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004234 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004235 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004236 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004237 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4238 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004239 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004240 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004241#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004242 if (ctx.old_flag != 0) {
4243 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004244 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004245 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004246#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004247 /*temp.nonnull = 0; - o_free does it below */
4248 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004249 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004250 /* Discard all unprocessed line input, force prompt on */
4251 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004252#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004253 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004254#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004255 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004256 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004257 /* loop on syntax errors, return on EOF: */
4258 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004259 return 0;
4260}
4261
Denis Vlasenko170435c2007-05-23 13:01:10 +00004262static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004263{
4264 struct in_str input;
4265 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004266 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004267}
4268
Denis Vlasenko170435c2007-05-23 13:01:10 +00004269static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004270{
4271 int rcode;
4272 struct in_str input;
4273 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004274 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004275 return rcode;
4276}
4277
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004278#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004279/* Make sure we have a controlling tty. If we get started under a job
4280 * aware app (like bash for example), make sure we are now in charge so
4281 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004282static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004283{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004284 pid_t shell_pgrp;
4285
Denis Vlasenko87a86552008-07-29 19:43:10 +00004286 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004287 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004288
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004289 /* If we were ran as 'hush &',
4290 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004291 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004292 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004293 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004294 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004295 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004296
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004297 /* Ignore job-control and misc signals. */
4298 set_jobctrl_sighandler(SIG_IGN);
4299 set_misc_sighandler(SIG_IGN);
4300//huh? signal(SIGCHLD, SIG_IGN);
4301
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004302 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004303 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004304
4305 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004306 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004307 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004308 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004309}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004310#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004311
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004312
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004313int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004314int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004315{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004316 static const struct variable const_shell_ver = {
4317 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004318 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004319 .max_len = 1, /* 0 can provoke free(name) */
4320 .flg_export = 1,
4321 .flg_read_only = 1,
4322 };
4323
Eric Andersen25f27032001-04-26 23:22:31 +00004324 int opt;
4325 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004326 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004327 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004328
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004329 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004330
Denis Vlasenko87a86552008-07-29 19:43:10 +00004331 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004332
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004333 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004334 G.shell_ver = const_shell_ver; /* copying struct here */
4335 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004336 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004337 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4338 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004339 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004340 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004341 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004342 if (e) while (*e) {
4343 char *value = strchr(*e, '=');
4344 if (value) { /* paranoia */
4345 cur_var->next = xzalloc(sizeof(*cur_var));
4346 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004347 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004348 cur_var->max_len = strlen(*e);
4349 cur_var->flg_export = 1;
4350 }
4351 e++;
4352 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004353 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004354 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004355
Denis Vlasenko38f63192007-01-22 09:03:07 +00004356#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004357 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004358#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004359 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004360 G.global_argc = argc;
4361 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004362 /* Initialize some more globals to non-zero values */
4363 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004364#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00004365 if (ENABLE_FEATURE_EDITING)
4366 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004367 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004368#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004369
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004370 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004371 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004372
4373 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004374 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004375 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004376 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004377 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004378 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004379 fclose(input);
4380 }
Eric Andersen25f27032001-04-26 23:22:31 +00004381 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004382 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004383
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004384 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4385 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00004386 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004387 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004388 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00004389 if (!argv[optind]) {
4390 /* -c 'script' (no params): prevent empty $0 */
4391 *--G.global_argv = argv[0];
4392 optind--;
4393 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004394 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004395 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004396 goto final_return;
4397 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004398 /* Well, we cannot just declare interactiveness,
4399 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004400 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004401 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00004402 case 's':
4403 /* "-s" means "read from stdin", but this is how we always
4404 * operate, so simply do nothing here. */
4405 break;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004406 case 'n':
4407 case 'x':
4408 if (!builtin_set_mode('-', opt))
4409 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004410 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004411#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004412 fprintf(stderr, "Usage: sh [FILE]...\n"
4413 " or: sh -c command [args]...\n\n");
4414 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004415#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004416 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004417#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004418 }
4419 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004420#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004421 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004422 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004423 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004424 * no arguments remaining or the -s flag given
4425 * standard input is a terminal
4426 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004427 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004428 if (argv[optind] == NULL && input == stdin
4429 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4430 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004431 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4432 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4433 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004434 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004435 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4436 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004437 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004438 G.interactive_fd = dup(STDIN_FILENO);
4439 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004440 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004441 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004442 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004443 // TODO: track & disallow any attempts of user
4444 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004445 }
Eric Andersen25f27032001-04-26 23:22:31 +00004446 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004447 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4448 if (G.interactive_fd) {
4449 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004450 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004451 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004452 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004453 * (we reset die_sleep = 0 whereever we [v]fork) */
4454 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004455 if (setjmp(die_jmp)) {
4456 /* xfunc has failed! die die die */
4457 hush_exit(xfunc_error_retval);
4458 }
Eric Andersenada18ff2001-05-21 16:18:22 +00004459 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004460#elif ENABLE_HUSH_INTERACTIVE
4461/* no job control compiled, only prompt/line editing */
4462 if (argv[optind] == NULL && input == stdin
4463 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4464 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004465 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4466 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004467 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004468 G.interactive_fd = dup(STDIN_FILENO);
4469 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004470 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004471 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004472 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004473 if (G.interactive_fd) {
4474 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004475 set_misc_sighandler(SIG_IGN);
4476 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004477 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004478#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004479
Denis Vlasenko701ac182009-03-28 19:22:08 +00004480#if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4481 if (G.interactive_fd) {
Mike Frysingerb2705e12009-03-23 08:44:02 +00004482 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4483 printf("Enter 'help' for a list of built-in commands.\n\n");
4484 }
Denis Vlasenko701ac182009-03-28 19:22:08 +00004485#endif
Mike Frysingerb2705e12009-03-23 08:44:02 +00004486
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004487 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004488 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004489 } else {
4490 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004491 G.global_argv = argv + optind;
4492 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004493 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004494 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004495 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004496 }
Eric Andersen25f27032001-04-26 23:22:31 +00004497
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004498 final_return:
4499
Denis Vlasenko38f63192007-01-22 09:03:07 +00004500#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004501 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004502 if (G.cwd != bb_msg_unknown)
4503 free((char*)G.cwd);
4504 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004505 while (cur_var) {
4506 struct variable *tmp = cur_var;
4507 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004508 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004509 cur_var = cur_var->next;
4510 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004511 }
Eric Andersen25f27032001-04-26 23:22:31 +00004512#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004513 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004514}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004515
4516
4517#if ENABLE_LASH
4518int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4519int lash_main(int argc, char **argv)
4520{
4521 //bb_error_msg("lash is deprecated, please use hush instead");
4522 return hush_main(argc, argv);
4523}
4524#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004525
4526
4527/*
4528 * Built-ins
4529 */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00004530/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_28
4531 *
4532 * Traps are also evaluated immediately instead of being delayed properly:
4533 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_11
4534 * Example: hush -c 'trap "echo hi" 31; sleep 10; echo moo' & sleep 1; kill -31 $!
4535 * "hi" should not be displayed until the sleep finishes
4536 * This will have to get fixed ...
4537 */
4538static void handle_trap(int sig)
4539{
4540 int save_errno, save_rcode;
4541 char *argv[] = { NULL, G.traps[sig].cmd, NULL };
4542 /* Race! We transitioned from handled to ignore/default, but
4543 * the signal came in after updating .cmd but before we could
4544 * register the new signal handler.
4545 */
4546 if (!argv[1] || argv[1][0] == '\0')
4547 return;
4548 /* need to save/restore errno/$? across traps */
4549 save_errno = errno;
4550 save_rcode = G.last_return_code;
4551 builtin_eval(argv);
4552 errno = save_errno;
4553 G.last_return_code = save_rcode;
4554}
4555static int builtin_trap(char **argv)
4556{
4557 size_t i;
4558 int sig;
4559 bool ign = false;
4560 char *new_cmd = NULL;
4561
4562 if (!G.traps)
4563 G.traps = xzalloc(sizeof(*G.traps) * NSIG);
4564
4565 if (!argv[1]) {
4566 /* No args: print all trapped. This isn't 100% correct as we should
4567 * be escaping the cmd so that it can be pasted back in ...
4568 */
4569 for (i = 0; i < NSIG; ++i)
4570 if (G.traps[i].cmd)
4571 printf("trap -- '%s' %s\n", G.traps[i].cmd, get_signame(i));
4572 return EXIT_SUCCESS;
4573 }
4574
4575 /* first arg is decimal: reset all specified */
4576 sig = bb_strtou(argv[1], NULL, 10);
4577 if (errno == 0) {
4578 int ret;
4579 i = 0;
4580 set_all:
4581 ret = EXIT_SUCCESS;
4582 while (argv[++i]) {
4583 char *old_cmd;
4584
4585 sig = get_signum(argv[i]);
4586 if (sig < 0 || sig >= NSIG) {
4587 ret = EXIT_FAILURE;
4588 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
4589 continue;
4590 }
4591
4592 /* Make sure .cmd is always a valid command list since
4593 * signals can occur at any time ...
4594 */
4595 old_cmd = G.traps[sig].cmd;
4596 G.traps[sig].cmd = xstrdup(new_cmd);
4597 free(old_cmd);
4598
4599 debug_printf("trap: setting SIG%s (%i) to: %s",
4600 get_signame(sig), sig, G.traps[sig].cmd);
4601
4602 /* There is no signal for 0 (EXIT) */
4603 if (sig == 0)
4604 continue;
4605
4606 if (new_cmd) {
4607 /* add/update a handler */
4608 struct sigaction act = {
4609 .sa_handler = ign ? SIG_IGN : handle_trap,
4610 .sa_flags = SA_RESTART,
4611 };
4612 sigemptyset(&act.sa_mask);
4613 sigaction(sig, &act, old_cmd ? NULL : &G.traps[sig].oact);
4614 } else if (old_cmd && !new_cmd)
4615 /* there was a handler, and we are removing it */
4616 sigaction_set(sig, &G.traps[sig].oact);
4617 }
4618 return ret;
4619 }
4620
4621 /* first arg is "-": reset all specified to default */
4622 /* first arg is "": ignore all specified */
4623 /* everything else: execute first arg upon signal */
4624 if (!argv[2]) {
4625 bb_error_msg("trap: invalid arguments");
4626 return EXIT_FAILURE;
4627 }
4628 if (LONE_DASH(argv[1]))
4629 /* nothing! */;
4630 else
4631 new_cmd = argv[1];
4632 if (argv[1][0] == '\0')
4633 ign = true;
4634 i = 1;
4635 goto set_all;
4636}
4637
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004638static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004639{
4640 return 0;
4641}
4642
4643static int builtin_test(char **argv)
4644{
4645 int argc = 0;
4646 while (*argv) {
4647 argc++;
4648 argv++;
4649 }
4650 return test_main(argc, argv - argc);
4651}
4652
4653static int builtin_echo(char **argv)
4654{
4655 int argc = 0;
4656 while (*argv) {
4657 argc++;
4658 argv++;
4659 }
4660 return echo_main(argc, argv - argc);
4661}
4662
4663static int builtin_eval(char **argv)
4664{
4665 int rcode = EXIT_SUCCESS;
4666
4667 if (argv[1]) {
4668 char *str = expand_strvec_to_string(argv + 1);
4669 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4670 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004671 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004672 }
4673 return rcode;
4674}
4675
4676static int builtin_cd(char **argv)
4677{
4678 const char *newdir;
4679 if (argv[1] == NULL) {
4680 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4681 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4682 newdir = getenv("HOME") ? : "/";
4683 } else
4684 newdir = argv[1];
4685 if (chdir(newdir)) {
4686 printf("cd: %s: %s\n", newdir, strerror(errno));
4687 return EXIT_FAILURE;
4688 }
4689 set_cwd();
4690 return EXIT_SUCCESS;
4691}
4692
4693static int builtin_exec(char **argv)
4694{
4695 if (argv[1] == NULL)
4696 return EXIT_SUCCESS; /* bash does this */
4697 {
4698#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004699 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004700#endif
4701// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004702 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004703 /* never returns */
4704 }
4705}
4706
4707static int builtin_exit(char **argv)
4708{
4709// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4710 //puts("exit"); /* bash does it */
4711// TODO: warn if we have background jobs: "There are stopped jobs"
4712// On second consecutive 'exit', exit anyway.
4713 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004714 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004715 /* mimic bash: exit 123abc == exit 255 + error msg */
4716 xfunc_error_retval = 255;
4717 /* bash: exit -2 == exit 254, no error msg */
4718 hush_exit(xatoi(argv[1]) & 0xff);
4719}
4720
4721static int builtin_export(char **argv)
4722{
4723 const char *value;
4724 char *name = argv[1];
4725
4726 if (name == NULL) {
4727 // TODO:
4728 // ash emits: export VAR='VAL'
4729 // bash: declare -x VAR="VAL"
4730 // (both also escape as needed (quotes, $, etc))
4731 char **e = environ;
4732 if (e)
4733 while (*e)
4734 puts(*e++);
4735 return EXIT_SUCCESS;
4736 }
4737
4738 value = strchr(name, '=');
4739 if (!value) {
4740 /* They are exporting something without a =VALUE */
4741 struct variable *var;
4742
4743 var = get_local_var(name);
4744 if (var) {
4745 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004746 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004747 putenv(var->varstr);
4748 }
4749 /* bash does not return an error when trying to export
4750 * an undefined variable. Do likewise. */
4751 return EXIT_SUCCESS;
4752 }
4753
4754 set_local_var(xstrdup(name), 1);
4755 return EXIT_SUCCESS;
4756}
4757
4758#if ENABLE_HUSH_JOB
4759/* built-in 'fg' and 'bg' handler */
4760static int builtin_fg_bg(char **argv)
4761{
4762 int i, jobnum;
4763 struct pipe *pi;
4764
Denis Vlasenko87a86552008-07-29 19:43:10 +00004765 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004766 return EXIT_FAILURE;
4767 /* If they gave us no args, assume they want the last backgrounded task */
4768 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004769 for (pi = G.job_list; pi; pi = pi->next) {
4770 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004771 goto found;
4772 }
4773 }
4774 bb_error_msg("%s: no current job", argv[0]);
4775 return EXIT_FAILURE;
4776 }
4777 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4778 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4779 return EXIT_FAILURE;
4780 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004781 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004782 if (pi->jobid == jobnum) {
4783 goto found;
4784 }
4785 }
4786 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4787 return EXIT_FAILURE;
4788 found:
4789 // TODO: bash prints a string representation
4790 // of job being foregrounded (like "sleep 1 | cat")
4791 if (*argv[0] == 'f') {
4792 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004793 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004794 }
4795
4796 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004797 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4798 for (i = 0; i < pi->num_cmds; i++) {
4799 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4800 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004801 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004802 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004803
4804 i = kill(- pi->pgrp, SIGCONT);
4805 if (i < 0) {
4806 if (errno == ESRCH) {
4807 delete_finished_bg_job(pi);
4808 return EXIT_SUCCESS;
4809 } else {
4810 bb_perror_msg("kill (SIGCONT)");
4811 }
4812 }
4813
4814 if (*argv[0] == 'f') {
4815 remove_bg_job(pi);
4816 return checkjobs_and_fg_shell(pi);
4817 }
4818 return EXIT_SUCCESS;
4819}
4820#endif
4821
4822#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004823static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004824{
4825 const struct built_in_command *x;
4826
4827 printf("\nBuilt-in commands:\n");
4828 printf("-------------------\n");
4829 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4830 printf("%s\t%s\n", x->cmd, x->descr);
4831 }
4832 printf("\n\n");
4833 return EXIT_SUCCESS;
4834}
4835#endif
4836
4837#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004838static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004839{
4840 struct pipe *job;
4841 const char *status_string;
4842
Denis Vlasenko87a86552008-07-29 19:43:10 +00004843 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004844 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004845 status_string = "Stopped";
4846 else
4847 status_string = "Running";
4848
4849 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4850 }
4851 return EXIT_SUCCESS;
4852}
4853#endif
4854
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004855static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004856{
4857 puts(set_cwd());
4858 return EXIT_SUCCESS;
4859}
4860
4861static int builtin_read(char **argv)
4862{
4863 char *string;
4864 const char *name = argv[1] ? argv[1] : "REPLY";
4865
4866 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4867 return set_local_var(string, 0);
4868}
4869
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004870/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4871 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004872 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004873 * set [-abCefhmnuvx] [-o option] [argument...]
4874 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004875 * set -- [argument...]
4876 * set -o
4877 * set +o
4878 * Implementations shall support the options in both their hyphen and
4879 * plus-sign forms. These options can also be specified as options to sh.
4880 * Examples:
4881 * Write out all variables and their values: set
4882 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4883 * Turn on the -x and -v options: set -xv
4884 * Unset all positional parameters: set --
4885 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4886 * Set the positional parameters to the expansion of x, even if x expands
4887 * with a leading '-' or '+': set -- $x
4888 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004889 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004890 */
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004891static int builtin_set_mode(const char cstate, const char mode)
4892{
4893 int state = (cstate == '-' ? 1 : 0);
4894 switch (mode) {
4895 case 'n': G.fake_mode = state; break;
4896 case 'x': /*G.debug_mode = state;*/ break;
4897 default: return EXIT_FAILURE;
4898 }
4899 return EXIT_SUCCESS;
4900}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004901static int builtin_set(char **argv)
4902{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004903 int n;
4904 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004905 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004906
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004907 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004908 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004909 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004910 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004911 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004912 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004913
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004914 do {
4915 if (!strcmp(arg, "--")) {
4916 ++argv;
4917 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004918 }
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004919
4920 if (arg[0] == '+' || arg[0] == '-') {
4921 for (n = 1; arg[n]; ++n)
4922 if (builtin_set_mode(arg[0], arg[n]))
4923 goto error;
4924 continue;
4925 }
4926
4927 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004928 } while ((arg = *++argv) != NULL);
4929 /* Now argv[0] is 1st argument */
4930
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004931 /* Only reset global_argv if we didn't process anything */
4932 if (arg == NULL)
4933 return EXIT_SUCCESS;
4934 set_argv:
4935
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004936 /* NB: G.global_argv[0] ($0) is never freed/changed */
4937 g_argv = G.global_argv;
4938 if (G.global_args_malloced) {
4939 pp = g_argv;
4940 while (*++pp)
4941 free(*pp);
4942 g_argv[1] = NULL;
4943 } else {
4944 G.global_args_malloced = 1;
4945 pp = xzalloc(sizeof(pp[0]) * 2);
4946 pp[0] = g_argv[0]; /* retain $0 */
4947 g_argv = pp;
4948 }
4949 /* This realloc's G.global_argv */
4950 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4951
4952 n = 1;
4953 while (*++pp)
4954 n++;
4955 G.global_argc = n;
4956
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004957 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00004958
4959 /* Nothing known, so abort */
4960 error:
4961 bb_error_msg("set: %s: invalid option", arg);
4962 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004963}
4964
4965static int builtin_shift(char **argv)
4966{
4967 int n = 1;
4968 if (argv[1]) {
4969 n = atoi(argv[1]);
4970 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004971 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004972 if (G.global_args_malloced) {
4973 int m = 1;
4974 while (m <= n)
4975 free(G.global_argv[m++]);
4976 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004977 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004978 memmove(&G.global_argv[1], &G.global_argv[n+1],
4979 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004980 return EXIT_SUCCESS;
4981 }
4982 return EXIT_FAILURE;
4983}
4984
4985static int builtin_source(char **argv)
4986{
4987 FILE *input;
4988 int status;
4989
4990 if (argv[1] == NULL)
4991 return EXIT_FAILURE;
4992
4993 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004994 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004995 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004996 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004997 return EXIT_FAILURE;
4998 }
4999 close_on_exec_on(fileno(input));
5000
5001 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005002 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005003 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00005004 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005005 status = parse_and_run_file(input);
5006 fclose(input);
5007 return status;
5008}
5009
5010static int builtin_umask(char **argv)
5011{
5012 mode_t new_umask;
5013 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005014 if (arg) {
Mike Frysinger40b8dc42009-03-29 00:50:30 +00005015 new_umask = bb_strtou(arg, NULL, 8);
5016 if (errno)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005017 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005018 } else {
5019 new_umask = umask(0);
5020 printf("%.3o\n", (unsigned) new_umask);
5021 }
5022 umask(new_umask);
5023 return EXIT_SUCCESS;
5024}
5025
5026static int builtin_unset(char **argv)
5027{
5028 /* bash always returns true */
5029 unset_local_var(argv[1]);
5030 return EXIT_SUCCESS;
5031}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005032
Mike Frysinger56bdea12009-03-28 20:01:58 +00005033/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5034static int builtin_wait(char **argv)
5035{
5036 int ret = EXIT_SUCCESS;
5037 int status;
5038
5039 if (argv[1] == NULL)
5040 /* don't care about exit status */
5041 wait(&status);
5042
5043 while (argv[1]) {
Mike Frysinger40b8dc42009-03-29 00:50:30 +00005044 pid_t pid = bb_strtou(argv[1], NULL, 10);
5045 if (errno) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00005046 bb_perror_msg("wait %s", argv[1]);
5047 return EXIT_FAILURE;
5048 } else if (waitpid(pid, &status, 0) == pid) {
5049 if (WIFSIGNALED(status))
5050 ret = 128 + WTERMSIG(status);
5051 else if (WIFEXITED(status))
5052 ret = WEXITSTATUS(status);
5053 else
5054 ret = EXIT_FAILURE;
5055 } else {
5056 bb_perror_msg("wait %s", argv[1]);
5057 ret = 127;
5058 }
5059 ++argv;
5060 }
5061
5062 return ret;
5063}
5064
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005065#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005066static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005067{
Denis Vlasenko87a86552008-07-29 19:43:10 +00005068 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005069 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00005070 return EXIT_SUCCESS; /* bash compat */
5071 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005072 G.flag_break_continue++; /* BC_BREAK = 1 */
5073 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005074 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005075 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5076 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005077 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00005078 G.flag_break_continue = BC_BREAK;
5079 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005080 }
5081 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00005082 if (G.depth_of_loop < G.depth_break_continue)
5083 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005084 return EXIT_SUCCESS;
5085}
5086
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00005087static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005088{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00005089 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5090 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00005091}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00005092#endif