blob: 3b87855b6a107841f959a1eb644ab4e9eccf73a9 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
3 * sh.c -- 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.
7 *
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 Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Denis Vlasenkoa8442002008-06-14 11:00:17 +000026 * 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 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
Eric Andersen25f27032001-04-26 23:22:31 +000041 * &> and >& redirection of stdout+stderr
42 * Brace Expansion
43 * Tilde Expansion
44 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000045 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000046 * Arithmetic Expansion
47 * <(list) and >(list) Process Substitution
Denis Vlasenko9af22c72008-10-09 12:54:58 +000048 * reserved words: select, function
Eric Andersen25f27032001-04-26 23:22:31 +000049 * Here Documents ( << word )
50 * Functions
51 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000052 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000053 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000054 * port selected bugfixes from post-0.49 busybox lash - done?
Eric Andersen83a2ae22001-05-07 17:59:25 +000055 * change { and } from special chars to reserved words
Denis Vlasenkobcb25532008-07-28 23:04:34 +000056 * builtins: return, trap, ulimit
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +000057 * test magic exec with redirection only
Eric Andersen25f27032001-04-26 23:22:31 +000058 * check setting of global_argc and global_argv
Eric Andersen25f27032001-04-26 23:22:31 +000059 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000060 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000061 * propagate syntax errors, die on resource errors?
62 * continuation lines, both explicit and implicit - done?
63 * memory leak finding and plugging - done?
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000064 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000065 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000066 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000067 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000068
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000069#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenko61befda2008-11-25 01:36:03 +000070//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
71//#include "applet_tables.h" doesn't work
Denis Vlasenkobe709c22008-07-28 00:01:16 +000072#include <glob.h>
73/* #include <dmalloc.h> */
74#if ENABLE_HUSH_CASE
75#include <fnmatch.h>
76#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +000077
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +000078#define HUSH_VER_STR "0.91"
Denis Vlasenkod01ff132007-05-02 21:40:23 +000079
Denis Vlasenko61befda2008-11-25 01:36:03 +000080#if defined SINGLE_APPLET_MAIN
81/* STANDALONE does not make sense, and won't compile */
82#undef CONFIG_FEATURE_SH_STANDALONE
83#undef ENABLE_FEATURE_SH_STANDALONE
84#undef USE_FEATURE_SH_STANDALONE
85#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
86#define ENABLE_FEATURE_SH_STANDALONE 0
87#define USE_FEATURE_SH_STANDALONE(...)
88#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
89#endif
90
Denis Vlasenko05743d72008-02-10 12:10:08 +000091#if !BB_MMU && ENABLE_HUSH_TICK
92//#undef ENABLE_HUSH_TICK
93//#define ENABLE_HUSH_TICK 0
94#warning On NOMMU, hush command substitution is dangerous.
95#warning Dont use it for commands which produce lots of output.
96#warning For more info see shell/hush.c, generate_stream_from_list().
97#endif
98
99#if !BB_MMU && ENABLE_HUSH_JOB
100#undef ENABLE_HUSH_JOB
101#define ENABLE_HUSH_JOB 0
102#endif
103
104#if !ENABLE_HUSH_INTERACTIVE
105#undef ENABLE_FEATURE_EDITING
106#define ENABLE_FEATURE_EDITING 0
107#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
108#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000109#endif
110
111
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000112/* Keep unconditionally on for now */
113#define HUSH_DEBUG 1
114/* In progress... */
115#define ENABLE_HUSH_FUNCTIONS 0
116
117
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000118/* If you comment out one of these below, it will be #defined later
119 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000120#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000121/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000122#define debug_printf_parse(...) do {} while (0)
123#define debug_print_tree(a, b) do {} while (0)
124#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000125#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000126#define debug_printf_jobs(...) do {} while (0)
127#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000128#define debug_printf_glob(...) do {} while (0)
129#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000130#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000131#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000132
133#ifndef debug_printf
134#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000135#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000136
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000137#ifndef debug_printf_parse
138#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000139#endif
140
141#ifndef debug_printf_exec
142#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
143#endif
144
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000145#ifndef debug_printf_env
146#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
147#endif
148
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000149#ifndef debug_printf_jobs
150#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000151#define DEBUG_JOBS 1
152#else
153#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000154#endif
155
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000156#ifndef debug_printf_expand
157#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
158#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000159#else
160#define DEBUG_EXPAND 0
161#endif
162
163#ifndef debug_printf_glob
164#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
165#define DEBUG_GLOB 1
166#else
167#define DEBUG_GLOB 0
168#endif
169
170#ifndef debug_printf_list
171#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000172#endif
173
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000174#ifndef debug_printf_subst
175#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
176#endif
177
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000178#ifndef debug_printf_clean
179/* broken, of course, but OK for testing */
180static const char *indenter(int i)
181{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000182 static const char blanks[] ALIGN1 =
183 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000184 return &blanks[sizeof(blanks) - i - 1];
185}
186#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000187#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000188#endif
189
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000190#if DEBUG_EXPAND
191static void debug_print_strings(const char *prefix, char **vv)
192{
193 fprintf(stderr, "%s:\n", prefix);
194 while (*vv)
195 fprintf(stderr, " '%s'\n", *vv++);
196}
197#else
198#define debug_print_strings(prefix, vv) ((void)0)
199#endif
200
Denis Vlasenkof962a032007-11-23 12:50:54 +0000201/*
202 * Leak hunting. Use hush_leaktool.sh for post-processing.
203 */
204#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000205/* suppress "warning: no previous prototype..." */
206void *xxmalloc(int lineno, size_t size);
207void *xxrealloc(int lineno, void *ptr, size_t size);
208char *xxstrdup(int lineno, const char *str);
209void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000210void *xxmalloc(int lineno, size_t size)
211{
212 void *ptr = xmalloc((size + 0xff) & ~0xff);
213 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
214 return ptr;
215}
216void *xxrealloc(int lineno, void *ptr, size_t size)
217{
218 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
219 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
220 return ptr;
221}
222char *xxstrdup(int lineno, const char *str)
223{
224 char *ptr = xstrdup(str);
225 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
226 return ptr;
227}
228void xxfree(void *ptr)
229{
230 fprintf(stderr, "free %p\n", ptr);
231 free(ptr);
232}
233#define xmalloc(s) xxmalloc(__LINE__, s)
234#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
235#define xstrdup(s) xxstrdup(__LINE__, s)
236#define free(p) xxfree(p)
237#endif
238
239
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000240/* Do we support ANY keywords? */
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000241#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000242#define HAS_KEYWORDS 1
243#define IF_HAS_KEYWORDS(...) __VA_ARGS__
244#define IF_HAS_NO_KEYWORDS(...)
245#else
246#define HAS_KEYWORDS 0
247#define IF_HAS_KEYWORDS(...)
248#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
249#endif
250
251
Denis Vlasenko5703c222008-06-15 11:49:42 +0000252#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000253#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000254
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000255typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000256 REDIRECT_INPUT = 1,
257 REDIRECT_OVERWRITE = 2,
258 REDIRECT_APPEND = 3,
259 REDIRECT_HEREIS = 4,
260 REDIRECT_IO = 5
261} redir_type;
262
Denis Vlasenko55789c62008-06-18 16:30:42 +0000263/* The descrip member of this structure is only used to make
264 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000265static const struct {
266 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000267 signed char default_fd;
268 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000269} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000270 { 0, 0, "()" },
271 { O_RDONLY, 0, "<" },
272 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
273 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
274 { O_RDONLY, -1, "<<" },
275 { O_RDWR, 1, "<>" }
276};
277
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000278typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000279 PIPE_SEQ = 1,
280 PIPE_AND = 2,
281 PIPE_OR = 3,
282 PIPE_BG = 4,
283} pipe_style;
284
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000285typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000286 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000287#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000288 RES_IF ,
289 RES_THEN ,
290 RES_ELIF ,
291 RES_ELSE ,
292 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000293#endif
294#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000295 RES_FOR ,
296 RES_WHILE ,
297 RES_UNTIL ,
298 RES_DO ,
299 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000300#endif
301#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000302 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000303#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000304#if ENABLE_HUSH_CASE
305 RES_CASE ,
306 /* two pseudo-keywords support contrived "case" syntax: */
307 RES_MATCH , /* "word)" */
308 RES_CASEI , /* "this command is inside CASE" */
309 RES_ESAC ,
310#endif
311 RES_XXXX ,
312 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000313} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000314
Eric Andersen25f27032001-04-26 23:22:31 +0000315struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000316 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000317 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000318 int fd; /* file descriptor being redirected */
319 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000320 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000321};
322
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000323struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000324 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000325 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000326 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000327 smallint grp_type;
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000328 struct pipe *group; /* if non-NULL, this "prog" is {} group,
329 * subshell, or a compound statement */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000330 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000331 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000332};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000333/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
334 * and on execution these are substituted with their values.
335 * Substitution can make _several_ words out of one argv[n]!
336 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000337 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000338 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000339#define GRP_NORMAL 0
340#define GRP_SUBSHELL 1
341#if ENABLE_HUSH_FUNCTIONS
342#define GRP_FUNCTION 2
343#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000344
345struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000346 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000347 int num_cmds; /* total number of commands in job */
348 int alive_cmds; /* number of commands running (not exited) */
349 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000350#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000351 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000352 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000353 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000354#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000355 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000356 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000357 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
358 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000359};
360
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000361/* This holds pointers to the various results of parsing */
362struct parse_context {
363 struct command *command;
364 struct pipe *list_head;
365 struct pipe *pipe;
366 struct redir_struct *pending_redirect;
367#if HAS_KEYWORDS
368 smallint ctx_res_w;
369 smallint ctx_inverted; /* "! cmd | cmd" */
370#if ENABLE_HUSH_CASE
371 smallint ctx_dsemicolon; /* ";;" seen */
372#endif
373 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
374 struct parse_context *stack;
375#endif
376};
377
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000378/* On program start, environ points to initial environment.
379 * putenv adds new pointers into it, unsetenv removes them.
380 * Neither of these (de)allocates the strings.
381 * setenv allocates new strings in malloc space and does putenv,
382 * and thus setenv is unusable (leaky) for shell's purposes */
383#define setenv(...) setenv_is_leaky_dont_use()
384struct variable {
385 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000386 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000387 int max_len; /* if > 0, name is part of initial env; else name is malloced */
388 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000389 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000390};
391
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000392typedef struct o_string {
Eric Andersen25f27032001-04-26 23:22:31 +0000393 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000394 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000395 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000396 /* Misnomer! it's not "quoting", it's "protection against globbing"!
397 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000398 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000399 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000400 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000401 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000402 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000403} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000404enum {
405 MAYBE_ASSIGNMENT = 0,
406 DEFINITELY_ASSIGNMENT = 1,
407 NOT_ASSIGNMENT = 2,
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000408 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000409};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000410/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000411#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000412
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000413/* I can almost use ordinary FILE*. Is open_memstream() universally
Eric Andersen25f27032001-04-26 23:22:31 +0000414 * available? Where is it documented? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000415typedef struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000416 const char *p;
417 /* eof_flag=1: last char in ->p is really an EOF */
418 char eof_flag; /* meaningless if ->p == NULL */
419 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000420#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000421 smallint promptme;
422 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000423#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000424 FILE *file;
425 int (*get) (struct in_str *);
426 int (*peek) (struct in_str *);
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000427} in_str;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000428#define i_getch(input) ((input)->get(input))
429#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000430
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000431enum {
432 CHAR_ORDINARY = 0,
433 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
434 CHAR_IFS = 2, /* treated as ordinary if quoted */
435 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000436};
437
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000438enum {
439 BC_BREAK = 1,
440 BC_CONTINUE = 2,
441};
442
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000443
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000444/* "Globals" within this file */
445
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000446/* Sorted roughly by size (smaller offsets == smaller code) */
447struct globals {
448#if ENABLE_HUSH_INTERACTIVE
449 /* 'interactive_fd' is a fd# open to ctty, if we have one
450 * _AND_ if we decided to act interactively */
451 int interactive_fd;
452 const char *PS1;
453 const char *PS2;
454#endif
455#if ENABLE_FEATURE_EDITING
456 line_input_t *line_input_state;
457#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000458 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000459 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000460#if ENABLE_HUSH_JOB
461 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000462 pid_t saved_tty_pgrp;
463 int last_jobid;
464 struct pipe *job_list;
465 struct pipe *toplevel_list;
466 smallint ctrl_z_flag;
467#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000468#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000469 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000470#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000471 smallint fake_mode;
472 /* these three support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000473 smalluint last_return_code;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000474 char **global_argv;
475 int global_argc;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000476#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000477 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000478 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000479#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000480 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000483 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000484#if ENABLE_FEATURE_SH_STANDALONE
485 struct nofork_save_area nofork_save;
486#endif
487#if ENABLE_HUSH_JOB
488 sigjmp_buf toplevel_jb;
489#endif
490 unsigned char charmap[256];
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
492};
493
494#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000495/* Not #defining name to G.name - this quickly gets unwieldy
496 * (too many defines). Also, I actually prefer to see when a variable
497 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000498#define INIT_G() do { \
499 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
500} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000501
502
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000503#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
504
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000505#if 1
506/* Normal */
507static void syntax(const char *msg)
508{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000509#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000510 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000511 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000512 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000513 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000514 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000515 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000516#else
517 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
518#endif
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000519}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000520
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000521#else
522/* Debug */
523static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000524{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000525#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoff182a32008-07-05 20:29:59 +0000526 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000527 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000528 fp("syntax error hush.c:%d", line);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000529#else
530 bb_error_msg_and_die("syntax error hush.c:%d", line);
531#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000532}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000533#define syntax(str) syntax_lineno(__LINE__)
534#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000535
536/* Index of subroutines: */
Eric Andersen25f27032001-04-26 23:22:31 +0000537/* in_str manipulations: */
538static int static_get(struct in_str *i);
539static int static_peek(struct in_str *i);
540static int file_get(struct in_str *i);
541static int file_peek(struct in_str *i);
542static void setup_file_in_str(struct in_str *i, FILE *f);
543static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000544/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000545#if !defined(DEBUG_CLEAN)
546#define free_pipe_list(head, indent) free_pipe_list(head)
547#define free_pipe(pi, indent) free_pipe(pi)
548#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000549static int free_pipe_list(struct pipe *head, int indent);
550static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000551/* really run the final data structures: */
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000552typedef struct nommu_save_t {
553 char **new_env;
554 char **old_env;
555 char **argv;
556} nommu_save_t;
Denis Vlasenko76d50412008-06-10 16:19:39 +0000557#if BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000558#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000559 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000560#define pseudo_exec(nommu_save, command, argv_expanded) \
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000561 pseudo_exec(command, argv_expanded)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000562#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000563static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
564static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
565static int setup_redirects(struct command *prog, int squirrel[]);
566static int run_list(struct pipe *pi);
Denis Vlasenko05743d72008-02-10 12:10:08 +0000567static int run_pipe(struct pipe *pi);
Eric Andersen25f27032001-04-26 23:22:31 +0000568/* data structure manipulation: */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000569static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
570static void initialize_context(struct parse_context *ctx);
571static int done_word(o_string *dest, struct parse_context *ctx);
572static int done_command(struct parse_context *ctx);
573static void done_pipe(struct parse_context *ctx, pipe_style type);
Eric Andersen25f27032001-04-26 23:22:31 +0000574/* primary string parsing: */
575static int redirect_dup_num(struct in_str *input);
576static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000577#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000578static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000579 struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000580#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000581static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000582static const char *lookup_param(const char *src);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000583static int handle_dollar(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000584 struct in_str *input);
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000585static int parse_stream(o_string *dest, struct parse_context *ctx, struct in_str *input0, const char *end_trigger);
Eric Andersen25f27032001-04-26 23:22:31 +0000586/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000587static int parse_and_run_stream(struct in_str *inp, int parse_flag);
588static int parse_and_run_string(const char *s, int parse_flag);
589static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000590/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000591static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000592#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000593static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000594static void insert_bg_job(struct pipe *pi);
595static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000596static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000597#else
598int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
599#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000600/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000601static char **expand_strvec_to_strvec(char **argv);
602/* used for eval */
603static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000604/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000605static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000606static struct variable *get_local_var(const char *name);
607static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000608static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000609
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000610
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000611static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
612
613
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000614static int glob_needed(const char *s)
615{
616 while (*s) {
617 if (*s == '\\')
618 s++;
619 if (*s == '*' || *s == '[' || *s == '?')
620 return 1;
621 s++;
622 }
623 return 0;
624}
625
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000626static int is_assignment(const char *s)
627{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000628 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000629 return 0;
630 s++;
631 while (isalnum(*s) || *s == '_')
632 s++;
633 return *s == '=';
634}
635
Denis Vlasenko55789c62008-06-18 16:30:42 +0000636/* Replace each \x with x in place, return ptr past NUL. */
637static char *unbackslash(char *src)
638{
639 char *dst = src;
640 while (1) {
641 if (*src == '\\')
642 src++;
643 if ((*dst++ = *src++) == '\0')
644 break;
645 }
646 return dst;
647}
648
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000649static char **add_strings_to_strings(char **strings, char **add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000650{
651 int i;
652 unsigned count1;
653 unsigned count2;
654 char **v;
655
656 v = strings;
657 count1 = 0;
658 if (v) {
659 while (*v) {
660 count1++;
661 v++;
662 }
663 }
664 count2 = 0;
665 v = add;
666 while (*v) {
667 count2++;
668 v++;
669 }
670 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
671 v[count1 + count2] = NULL;
672 i = count2;
673 while (--i >= 0)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000674 v[count1 + i] = add[i];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000675 return v;
676}
677
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000678static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000679{
680 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000681 v[0] = add;
682 v[1] = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000683 return add_strings_to_strings(strings, v);
684}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000685
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000686static void putenv_all(char **strings)
687{
688 if (!strings)
689 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000690 while (*strings) {
691 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000692 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000693 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000694}
695
696static char **putenv_all_and_save_old(char **strings)
697{
698 char **old = NULL;
699 char **s = strings;
700
701 if (!strings)
702 return old;
703 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000704 char *v, *eq;
705
706 eq = strchr(*strings, '=');
707 if (eq) {
708 *eq = '\0';
709 v = getenv(*strings);
710 *eq = '=';
711 if (v) {
712 /* v points to VAL in VAR=VAL, go back to VAR */
713 v -= (eq - *strings) + 1;
714 old = add_string_to_strings(old, v);
715 }
716 }
717 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000718 }
719 putenv_all(s);
720 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000721}
722
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000723static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000724{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000725 char **v;
726
727 if (!strings)
728 return;
729
730 v = strings;
731 while (*v) {
732 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000733 debug_printf_env("unsetenv '%s'\n", *v);
734 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000735 }
736 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000737 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000738 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000739}
740
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000741static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000742{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000743 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000744}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000745
746
Denis Vlasenko83506862007-11-23 13:11:42 +0000747/* Function prototypes for builtins */
748static int builtin_cd(char **argv);
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000749static int builtin_echo(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000750static int builtin_eval(char **argv);
751static int builtin_exec(char **argv);
752static int builtin_exit(char **argv);
753static int builtin_export(char **argv);
754#if ENABLE_HUSH_JOB
755static int builtin_fg_bg(char **argv);
756static int builtin_jobs(char **argv);
757#endif
758#if ENABLE_HUSH_HELP
759static int builtin_help(char **argv);
760#endif
761static int builtin_pwd(char **argv);
762static int builtin_read(char **argv);
763static int builtin_test(char **argv);
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000764static int builtin_true(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000765static int builtin_set(char **argv);
766static int builtin_shift(char **argv);
767static int builtin_source(char **argv);
768static int builtin_umask(char **argv);
769static int builtin_unset(char **argv);
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000770#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000771static int builtin_break(char **argv);
772static int builtin_continue(char **argv);
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000773#endif
Denis Vlasenko83506862007-11-23 13:11:42 +0000774//static int builtin_not_written(char **argv);
775
Eric Andersen25f27032001-04-26 23:22:31 +0000776/* Table of built-in functions. They can be forked or not, depending on
777 * context: within pipes, they fork. As simple commands, they do not.
778 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000779 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000780 * For example, 'unset foo | whatever' will parse and run, but foo will
781 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000782struct built_in_command {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000783 const char *cmd;
784 int (*function)(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000785#if ENABLE_HUSH_HELP
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000786 const char *descr;
Denis Vlasenko06810332007-05-21 23:30:54 +0000787#define BLTIN(cmd, func, help) { cmd, func, help }
788#else
789#define BLTIN(cmd, func, help) { cmd, func }
790#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000791};
792
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000793/* For now, echo and test are unconditionally enabled.
794 * Maybe make it configurable? */
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000795static const struct built_in_command bltins[] = {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000796 BLTIN("." , builtin_source, "Run commands in a file"),
797 BLTIN(":" , builtin_true, "No-op"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000798 BLTIN("[" , builtin_test, "Test condition"),
799 BLTIN("[[" , builtin_test, "Test condition"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000800#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000801 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000802#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000803#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000804 BLTIN("break" , builtin_break, "Exit from a loop"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000805#endif
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000806 BLTIN("cd" , builtin_cd, "Change directory"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000807#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000808 BLTIN("continue", builtin_continue, "Start new loop iteration"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000809#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000810 BLTIN("echo" , builtin_echo, "Write to stdout"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000811 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000812 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
813 BLTIN("exit" , builtin_exit, "Exit"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000814 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000815#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000816 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000817 BLTIN("jobs" , builtin_jobs, "List active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000818#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000819 BLTIN("pwd" , builtin_pwd, "Print current directory"),
820 BLTIN("read" , builtin_read, "Input environment variable"),
821// BLTIN("return", builtin_not_written, "Return from a function"),
822 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
823 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
824// BLTIN("trap" , builtin_not_written, "Trap signals"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000825 BLTIN("test" , builtin_test, "Test condition"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000826// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
827 BLTIN("umask" , builtin_umask, "Set file creation mask"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000828 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000829#if ENABLE_HUSH_HELP
830 BLTIN("help" , builtin_help, "List shell built-in commands"),
831#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000832};
833
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000834
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000835/* Signals are grouped, we handle them in batches */
836static void set_misc_sighandler(void (*handler)(int))
837{
838 bb_signals(0
839 + (1 << SIGINT)
840 + (1 << SIGQUIT)
841 + (1 << SIGTERM)
842 , handler);
843}
844
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000845#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000846
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000847static void set_fatal_sighandler(void (*handler)(int))
848{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000849 bb_signals(0
850 + (1 << SIGILL)
851 + (1 << SIGTRAP)
852 + (1 << SIGABRT)
853 + (1 << SIGFPE)
854 + (1 << SIGBUS)
855 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000856 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000857 + (1 << SIGHUP)
858 + (1 << SIGPIPE)
859 + (1 << SIGALRM)
860 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000861}
862static void set_jobctrl_sighandler(void (*handler)(int))
863{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000864 bb_signals(0
865 + (1 << SIGTSTP)
866 + (1 << SIGTTIN)
867 + (1 << SIGTTOU)
868 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000869}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000870/* SIGCHLD is special and handled separately */
871
872static void set_every_sighandler(void (*handler)(int))
873{
874 set_fatal_sighandler(handler);
875 set_jobctrl_sighandler(handler);
876 set_misc_sighandler(handler);
877 signal(SIGCHLD, handler);
878}
879
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000880static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000881{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000882 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000883// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000884 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000885}
886
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000887static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000888{
889 pid_t pid;
890
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000891 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000892 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000893 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000894 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000895 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000896 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000897 if (ENABLE_HUSH_JOB)
898 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000899 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000900 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000901 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000902 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000903 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000904 /* return to nofork, it will eventually exit now,
905 * not return back to shell */
906 return;
907 }
908 /* parent */
909 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000910 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000911 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000912 /* parent needs to longjmp out of running nofork.
913 * we will "return" exitcode 0, with child put in background */
914// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000915 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000916 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000917}
918
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000919/* Restores tty foreground process group, and exits.
920 * May be called as signal handler for fatal signal
921 * (will faithfully resend signal to itself, producing correct exit state)
922 * or called directly with -EXITCODE.
923 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000924static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000925static void sigexit(int sig)
926{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000927 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000928 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000929
Denis Vlasenko87a86552008-07-29 19:43:10 +0000930#if ENABLE_HUSH_INTERACTIVE
931 if (G.interactive_fd)
932 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
933#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000934
935 /* Not a signal, just exit */
936 if (sig <= 0)
937 _exit(- sig);
938
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000939 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000940}
941
942/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000943static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000944static void hush_exit(int exitcode)
945{
946 fflush(NULL); /* flush all streams */
947 sigexit(- (exitcode & 0xff));
948}
949
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000950#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000951
952#define set_fatal_sighandler(handler) ((void)0)
953#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000954#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000955
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000956#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000957
958
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000959static const char *set_cwd(void)
960{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000961 if (G.cwd == bb_msg_unknown)
962 G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
963 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
964 if (!G.cwd)
965 G.cwd = bb_msg_unknown;
966 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000967}
968
Denis Vlasenko83506862007-11-23 13:11:42 +0000969
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000970/*
971 * o_string support
972 */
973#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +0000974
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000975static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000976{
977 o->length = 0;
978 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000979 if (o->data)
980 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000981}
982
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000983static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000984{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +0000985 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000986 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +0000987}
988
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000989static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000990{
991 if (o->length + len > o->maxlen) {
992 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
993 o->data = xrealloc(o->data, 1 + o->maxlen);
994 }
995}
996
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000997static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000998{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000999 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1000 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001001 o->data[o->length] = ch;
1002 o->length++;
1003 o->data[o->length] = '\0';
1004}
1005
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001006static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001007{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001008 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001009 memcpy(&o->data[o->length], str, len);
1010 o->length += len;
1011 o->data[o->length] = '\0';
1012}
1013
Denis Vlasenko55789c62008-06-18 16:30:42 +00001014static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1015{
1016 while (len) {
1017 o_addchr(o, *str);
1018 if (*str++ == '\\'
1019 && (*str != '*' && *str != '?' && *str != '[')
1020 ) {
1021 o_addchr(o, '\\');
1022 }
1023 len--;
1024 }
1025}
1026
Eric Andersen25f27032001-04-26 23:22:31 +00001027/* My analysis of quoting semantics tells me that state information
1028 * is associated with a destination, not a source.
1029 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001030static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001031{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001032 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001033 char *found = strchr("*?[\\", ch);
1034 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001035 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001036 o_grow_by(o, sz);
1037 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001038 o->data[o->length] = '\\';
1039 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001040 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001041 o->data[o->length] = ch;
1042 o->length++;
1043 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001044}
1045
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001046static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001047{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001048 int sz = 1;
1049 if (o->o_quote && strchr("*?[\\", ch)) {
1050 sz++;
1051 o->data[o->length] = '\\';
1052 o->length++;
1053 }
1054 o_grow_by(o, sz);
1055 o->data[o->length] = ch;
1056 o->length++;
1057 o->data[o->length] = '\0';
1058}
1059
1060static void o_addQstr(o_string *o, const char *str, int len)
1061{
1062 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001063 o_addstr(o, str, len);
1064 return;
1065 }
1066 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001067 char ch;
1068 int sz;
1069 int ordinary_cnt = strcspn(str, "*?[\\");
1070 if (ordinary_cnt > len) /* paranoia */
1071 ordinary_cnt = len;
1072 o_addstr(o, str, ordinary_cnt);
1073 if (ordinary_cnt == len)
1074 return;
1075 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001076 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001077
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001078 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001079 sz = 1;
1080 if (ch) { /* it is necessarily one of "*?[\\" */
1081 sz++;
1082 o->data[o->length] = '\\';
1083 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001084 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001085 o_grow_by(o, sz);
1086 o->data[o->length] = ch;
1087 o->length++;
1088 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001089 }
1090}
1091
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001092/* A special kind of o_string for $VAR and `cmd` expansion.
1093 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001094 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001095 * list[i] contains an INDEX (int!) into this string data.
1096 * It means that if list[] needs to grow, data needs to be moved higher up
1097 * but list[i]'s need not be modified.
1098 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001099 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001100 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1101 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001102#if DEBUG_EXPAND || DEBUG_GLOB
1103static void debug_print_list(const char *prefix, o_string *o, int n)
1104{
1105 char **list = (char**)o->data;
1106 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1107 int i = 0;
1108 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1109 prefix, list, n, string_start, o->length, o->maxlen);
1110 while (i < n) {
1111 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1112 o->data + (int)list[i] + string_start,
1113 o->data + (int)list[i] + string_start);
1114 i++;
1115 }
1116 if (n) {
1117 const char *p = o->data + (int)list[n - 1] + string_start;
1118 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1119 }
1120}
1121#else
1122#define debug_print_list(prefix, o, n) ((void)0)
1123#endif
1124
1125/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1126 * in list[n] so that it points past last stored byte so far.
1127 * It returns n+1. */
1128static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001129{
1130 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001131 int string_start;
1132 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001133
1134 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001135 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1136 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001137 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001138 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001139 /* list[n] points to string_start, make space for 16 more pointers */
1140 o->maxlen += 0x10 * sizeof(list[0]);
1141 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001142 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001143 memmove(list + n + 0x10, list + n, string_len);
1144 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001145 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001146 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001147 } else {
1148 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001149 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1150 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001151 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001152 o->has_empty_slot = 0;
1153 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001154 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001155 return n + 1;
1156}
1157
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001158/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001159static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001160{
1161 char **list = (char**)o->data;
1162 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1163
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001164 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001165}
1166
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001167/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001168 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001169static int o_glob(o_string *o, int n)
1170{
1171 glob_t globdata;
1172 int gr;
1173 char *pattern;
1174
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001175 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001176 if (!o->data)
1177 return o_save_ptr_helper(o, n);
1178 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001179 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001180 if (!glob_needed(pattern)) {
1181 literal:
1182 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001183 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001184 return o_save_ptr_helper(o, n);
1185 }
1186
1187 memset(&globdata, 0, sizeof(globdata));
1188 gr = glob(pattern, 0, NULL, &globdata);
1189 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1190 if (gr == GLOB_NOSPACE)
1191 bb_error_msg_and_die("out of memory during glob");
1192 if (gr == GLOB_NOMATCH) {
1193 globfree(&globdata);
1194 goto literal;
1195 }
1196 if (gr != 0) { /* GLOB_ABORTED ? */
1197//TODO: testcase for bad glob pattern behavior
1198 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1199 }
1200 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1201 char **argv = globdata.gl_pathv;
1202 o->length = pattern - o->data; /* "forget" pattern */
1203 while (1) {
1204 o_addstr(o, *argv, strlen(*argv) + 1);
1205 n = o_save_ptr_helper(o, n);
1206 argv++;
1207 if (!*argv)
1208 break;
1209 }
1210 }
1211 globfree(&globdata);
1212 if (DEBUG_GLOB)
1213 debug_print_list("o_glob returning", o, n);
1214 return n;
1215}
1216
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001217/* If o->o_glob == 1, glob the string so far remembered.
1218 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001219static int o_save_ptr(o_string *o, int n)
1220{
1221 if (o->o_glob)
1222 return o_glob(o, n); /* o_save_ptr_helper is inside */
1223 return o_save_ptr_helper(o, n);
1224}
1225
1226/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001227static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001228{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001229 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001230 int string_start;
1231
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001232 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1233 if (DEBUG_EXPAND)
1234 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001235 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001236 list = (char**)o->data;
1237 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1238 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001239 while (n) {
1240 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001241 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001242 }
1243 return list;
1244}
1245
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001246
1247/*
1248 * in_str support
1249 */
Eric Andersen25f27032001-04-26 23:22:31 +00001250static int static_get(struct in_str *i)
1251{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001252 int ch = *i->p++;
1253 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001254 return ch;
1255}
1256
1257static int static_peek(struct in_str *i)
1258{
1259 return *i->p;
1260}
1261
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001262#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001263
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001264#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001265static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001266{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001267#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denis Vlasenko87a86552008-07-29 19:43:10 +00001268 G.PS1 = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00001269#else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001270 G.PS1 = getenv("PS1");
1271 if (G.PS1 == NULL)
1272 G.PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001273#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001274}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001275#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001276
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001277static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001278{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001279 const char *prompt_str;
1280 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001281#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001282 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001283 if (promptmode == 0) { /* PS1 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001284 free((char*)G.PS1);
1285 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1286 prompt_str = G.PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001287 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001288 prompt_str = G.PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001289 }
1290#else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001291 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001292#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001293 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001294 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001295}
1296
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001297static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001298{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001299 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001300 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001301
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001302 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001303#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001304 /* Enable command line editing only while a command line
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001305 * is actually being read */
1306 do {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001307 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001308 } while (r == 0); /* repeat if Ctrl-C */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001309 i->eof_flag = (r < 0);
1310 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001311 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1312 G.user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001313 }
Eric Andersen25f27032001-04-26 23:22:31 +00001314#else
1315 fputs(prompt_str, stdout);
1316 fflush(stdout);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001317 G.user_input_buf[0] = r = fgetc(i->file);
1318 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001319 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001320#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00001321 i->p = G.user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001322}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001323
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001324#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001325
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001326/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001327 * and gets data back from the user */
1328static int file_get(struct in_str *i)
1329{
1330 int ch;
1331
Eric Andersen25f27032001-04-26 23:22:31 +00001332 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001333 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001334#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001335 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001336#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001337 ch = *i->p++;
1338 if (i->eof_flag && !*i->p)
1339 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001340 } else {
1341 /* need to double check i->file because we might be doing something
1342 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001343#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +00001344 if (G.interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001345 do {
1346 get_user_input(i);
1347 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001348 i->promptmode = 1; /* PS2 */
1349 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001350 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001351 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001352#endif
1353 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001354 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001355 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001356#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001357 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001358 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001359#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001360 return ch;
1361}
1362
1363/* All the callers guarantee this routine will never be
1364 * used right after a newline, so prompting is not needed.
1365 */
1366static int file_peek(struct in_str *i)
1367{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001368 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001369 if (i->p && *i->p) {
1370 if (i->eof_flag && !i->p[1])
1371 return EOF;
1372 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001373 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001374 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001375 i->eof_flag = (ch == EOF);
1376 i->peek_buf[0] = ch;
1377 i->peek_buf[1] = '\0';
1378 i->p = i->peek_buf;
1379 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001380 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001381}
1382
1383static void setup_file_in_str(struct in_str *i, FILE *f)
1384{
1385 i->peek = file_peek;
1386 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001387#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001388 i->promptme = 1;
1389 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001390#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001391 i->file = f;
1392 i->p = NULL;
1393}
1394
1395static void setup_string_in_str(struct in_str *i, const char *s)
1396{
1397 i->peek = static_peek;
1398 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001399#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001400 i->promptme = 1;
1401 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001402#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001403 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001404 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001405}
1406
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001407
Eric Andersen25f27032001-04-26 23:22:31 +00001408/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1409 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001410static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001411{
1412 int openfd, mode;
1413 struct redir_struct *redir;
1414
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001415 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001416 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001417 /* something went wrong in the parse. Pretend it didn't happen */
1418 continue;
1419 }
Eric Andersen25f27032001-04-26 23:22:31 +00001420 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001421 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001422 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001423//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001424 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001425 openfd = open_or_warn(p, mode);
1426 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001427 if (openfd < 0) {
1428 /* this could get lost if stderr has been redirected, but
1429 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001430 return 1;
1431 }
1432 } else {
1433 openfd = redir->dup;
1434 }
1435
1436 if (openfd != redir->fd) {
1437 if (squirrel && redir->fd < 3) {
1438 squirrel[redir->fd] = dup(redir->fd);
1439 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001440 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001441 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001442 } else {
1443 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001444 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001445 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001446 }
Eric Andersen25f27032001-04-26 23:22:31 +00001447 }
1448 }
1449 return 0;
1450}
1451
1452static void restore_redirects(int squirrel[])
1453{
1454 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001455 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001456 fd = squirrel[i];
1457 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001458 /* We simply die on error */
1459 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001460 }
1461 }
1462}
1463
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001464static char **expand_assignments(char **argv, int count)
1465{
1466 int i;
1467 char **p = NULL;
1468 /* Expand assignments into one string each */
1469 for (i = 0; i < count; i++) {
1470 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1471 }
1472 return p;
1473}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001474
Denis Vlasenko05743d72008-02-10 12:10:08 +00001475/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001476 * Never returns.
1477 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001478 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001479 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001480static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001481{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001482 int rcode;
1483 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001484 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001485
Denis Vlasenko1359da62007-04-21 23:27:30 +00001486 /* If a variable is assigned in a forest, and nobody listens,
1487 * was it ever really set?
1488 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001489 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001490 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001491
Denis Vlasenko9504e442008-10-29 01:19:15 +00001492 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001493#if BB_MMU
1494 putenv_all(new_env);
1495 free(new_env); /* optional */
1496#else
1497 nommu_save->new_env = new_env;
1498 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001499#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001500 if (argv_expanded) {
1501 argv = argv_expanded;
1502 } else {
1503 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001504#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001505 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00001506#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001507 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001508
Denis Vlasenko1359da62007-04-21 23:27:30 +00001509 /*
1510 * Check if the command matches any of the builtins.
1511 * Depending on context, this might be redundant. But it's
1512 * easier to waste a few CPU cycles than it is to figure out
1513 * if this is one of those cases.
1514 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001515 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001516 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001517 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001518 rcode = x->function(argv);
1519 fflush(stdout);
1520 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001521 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001522 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001523
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001524 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001525#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001526 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001527 int a = find_applet_by_name(argv[0]);
1528 if (a >= 0) {
1529 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001530 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001531// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1532 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001533 }
1534 /* re-exec ourselves with the new arguments */
1535 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001536 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001537 /* If they called chroot or otherwise made the binary no longer
1538 * executable, fall through */
1539 }
1540 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001541#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001542
1543 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001544 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00001545 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001546 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001547}
1548
Denis Vlasenko05743d72008-02-10 12:10:08 +00001549/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001550 */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001551static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001552{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001553 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001554 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001555
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001556 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001557#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001558 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001559#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001560 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001561 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001562 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001563 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001564 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001565 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001566#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001567 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001568
1569 /* Can happen. See what bash does with ">foo" by itself. */
1570 debug_printf("trying to pseudo_exec null command\n");
1571 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001572}
1573
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001574#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001575static const char *get_cmdtext(struct pipe *pi)
1576{
1577 char **argv;
1578 char *p;
1579 int len;
1580
1581 /* This is subtle. ->cmdtext is created only on first backgrounding.
1582 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001583 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001584 if (pi->cmdtext)
1585 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001586 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001587 if (!argv || !argv[0]) {
1588 pi->cmdtext = xzalloc(1);
1589 return pi->cmdtext;
1590 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001591
1592 len = 0;
1593 do len += strlen(*argv) + 1; while (*++argv);
1594 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001595 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001596 do {
1597 len = strlen(*argv);
1598 memcpy(p, *argv, len);
1599 p += len;
1600 *p++ = ' ';
1601 } while (*++argv);
1602 p[-1] = '\0';
1603 return pi->cmdtext;
1604}
1605
Eric Andersenbafd94f2001-05-02 16:11:59 +00001606static void insert_bg_job(struct pipe *pi)
1607{
1608 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001609 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001610
1611 /* Linear search for the ID of the job to use */
1612 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001613 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001614 if (thejob->jobid >= pi->jobid)
1615 pi->jobid = thejob->jobid + 1;
1616
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001617 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001618 if (!G.job_list) {
1619 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001620 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001621 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001622 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001623 thejob->next = xmalloc(sizeof(*thejob));
1624 thejob = thejob->next;
1625 }
1626
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001627 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001628 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001629 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
1630 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
1631 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001632// TODO: do we really need to have so many fields which are just dead weight
1633// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001634 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001635 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001636 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001637 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001638 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001639
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001640 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001641 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001642 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
1643 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001644 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001645}
1646
Eric Andersenbafd94f2001-05-02 16:11:59 +00001647static void remove_bg_job(struct pipe *pi)
1648{
1649 struct pipe *prev_pipe;
1650
Denis Vlasenko87a86552008-07-29 19:43:10 +00001651 if (pi == G.job_list) {
1652 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001653 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001654 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001655 while (prev_pipe->next != pi)
1656 prev_pipe = prev_pipe->next;
1657 prev_pipe->next = pi->next;
1658 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001659 if (G.job_list)
1660 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00001661 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001662 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001663}
Eric Andersen028b65b2001-06-28 01:10:11 +00001664
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001665/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001666static void delete_finished_bg_job(struct pipe *pi)
1667{
1668 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001669 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001670 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001671 free(pi);
1672}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001673#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001674
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001675/* Check to see if any processes have exited -- if they
1676 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001677static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001678{
Eric Andersenc798b072001-06-22 06:23:03 +00001679 int attributes;
1680 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001681#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001682 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001683#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001684 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001685 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001686
Eric Andersenc798b072001-06-22 06:23:03 +00001687 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001688 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00001689 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00001690
Denis Vlasenko1359da62007-04-21 23:27:30 +00001691/* Do we do this right?
1692 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001693 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001694 * [3]+ Stopped sleep 20 | false
1695 * bash-3.00# echo $?
1696 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1697 */
1698
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001699//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1700//are stopped. Testcase: "cat | cat" in a script (not on command line)
1701// + killall -STOP cat
1702
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001703 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00001704// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00001705 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001706 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001707 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001708#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00001709 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001710 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001711 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1712 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001713 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001714 childpid, WTERMSIG(status), WEXITSTATUS(status));
1715 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001716 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001717 childpid, WEXITSTATUS(status));
1718#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001719 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001720 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001721 for (i = 0; i < fg_pipe->num_cmds; i++) {
1722 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
1723 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001724 continue;
1725 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1726 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001727 fg_pipe->cmds[i].pid = 0;
1728 fg_pipe->alive_cmds--;
1729 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001730 /* last process gives overall exitstatus */
1731 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001732 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001733 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001734 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001735 fg_pipe->cmds[i].is_stopped = 1;
1736 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00001737 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001738 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
1739 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
1740 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001741 /* All processes in fg pipe have exited/stopped */
1742#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001743 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001744 insert_bg_job(fg_pipe);
1745#endif
1746 return rcode;
1747 }
1748 /* There are still running processes in the fg pipe */
1749 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00001750 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001751 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001752 }
1753
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001754#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001755 /* We asked to wait for bg or orphaned children */
1756 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001757 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001758 for (i = 0; i < pi->num_cmds; i++) {
1759 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001760 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001761 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001762 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001763 /* Happens when shell is used as init process (init=/bin/sh) */
1764 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001765 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00001766
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001767 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001768 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001769 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001770 pi->cmds[i].pid = 0;
1771 pi->alive_cmds--;
1772 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001773 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001774 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001775 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001776 }
1777 } else {
1778 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001779 pi->cmds[i].is_stopped = 1;
1780 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001781 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001782#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001783 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001784
Denis Vlasenko1359da62007-04-21 23:27:30 +00001785 /* wait found no children or failed */
1786
1787 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001788 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001789 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001790}
1791
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001792#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001793static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1794{
1795 pid_t p;
1796 int rcode = checkjobs(fg_pipe);
1797 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001798 p = getpgid(0); /* pgid of our process */
1799 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001800 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001801 return rcode;
1802}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001803#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001804
Denis Vlasenko05743d72008-02-10 12:10:08 +00001805/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001806 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001807 *
1808 * return code is normally -1, when the caller has to wait for children
1809 * to finish to determine the exit status of the pipe. If the pipe
1810 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00001811 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00001812 * return value.
1813 *
1814 * The input of the pipe is always stdin, the output is always
1815 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1816 * because it tries to avoid running the command substitution in
1817 * subshell, when that is in fact necessary. The subshell process
1818 * now has its stdout directed to the input of the appropriate pipe,
1819 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001820 *
1821 * Returns -1 only if started some children. IOW: we have to
1822 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001823 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001824static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001825{
1826 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001827 int nextin;
1828 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001829 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001830 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001831 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001832 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001833 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001834 /* it is not always needed, but we aim to smaller code */
1835 int squirrel[] = { -1, -1, -1 };
1836 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001837 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001838
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001839 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001840
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001841#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001842 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001843#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001844 pi->alive_cmds = 1;
1845 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001846
1847 /* Check if this is a simple builtin (not part of a pipe).
1848 * Builtins within pipes have to fork anyway, and are handled in
1849 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1850 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001851 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001852
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001853#if ENABLE_HUSH_FUNCTIONS
1854 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
1855 /* We "execute" function definition */
1856 bb_error_msg("here we ought to remember function definition, and go on");
1857 return EXIT_SUCCESS;
1858 }
1859#endif
1860
1861 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00001862 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001863 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001864 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001865 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00001866 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001867 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001868 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00001869 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001870 }
1871
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001872 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001873 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001874
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001875 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001876 char **new_env = NULL;
1877 char **old_env = NULL;
1878
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001879 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001880 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001881 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001882 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001883 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001884 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001885 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001886 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001887 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00001888 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001889
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001890 /* Expand the rest into (possibly) many strings each */
1891 argv_expanded = expand_strvec_to_strvec(argv + i);
1892
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001893 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001894 if (strcmp(argv_expanded[0], x->cmd) != 0)
1895 continue;
1896 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
1897 debug_printf("exec with redirects only\n");
1898 setup_redirects(command, NULL);
1899 rcode = EXIT_SUCCESS;
1900 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00001901 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001902 debug_printf("builtin inline %s\n", argv_expanded[0]);
1903 /* XXX setup_redirects acts on file descriptors, not FILEs.
1904 * This is perfect for work that comes after exec().
1905 * Is it really safe for inline use? Experimentally,
1906 * things seem to work with glibc. */
1907 setup_redirects(command, squirrel);
1908 new_env = expand_assignments(argv, command->assignment_cnt);
1909 old_env = putenv_all_and_save_old(new_env);
1910 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
1911 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001912#if ENABLE_FEATURE_SH_STANDALONE
1913 clean_up_and_ret:
1914#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001915 restore_redirects(squirrel);
1916 free_strings_and_unsetenv(new_env, 1);
1917 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001918 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001919 clean_up_and_ret1:
1920 free(argv_expanded);
1921 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1922 debug_printf_exec("run_pipe return %d\n", rcode);
1923 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00001924 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001925#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001926 i = find_applet_by_name(argv_expanded[0]);
1927 if (i >= 0 && APPLET_IS_NOFORK(i)) {
1928 setup_redirects(command, squirrel);
1929 save_nofork_data(&G.nofork_save);
1930 new_env = expand_assignments(argv, command->assignment_cnt);
1931 old_env = putenv_all_and_save_old(new_env);
1932 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1933 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
1934 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001935 }
1936#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001937 }
1938
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001939 /* NB: argv_expanded may already be created, and that
1940 * might include `cmd` runs! Do not rerun it! We *must*
1941 * use argv_expanded if it's non-NULL */
1942
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001943 /* Disable job control signals for shell (parent) and
1944 * for initial child code after fork */
1945 set_jobctrl_sighandler(SIG_IGN);
1946
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001947 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001948 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001949 nextin = 0;
1950
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001951 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00001952#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001953 volatile nommu_save_t nommu_save;
1954 nommu_save.new_env = NULL;
1955 nommu_save.old_env = NULL;
1956 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00001957#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001958 command = &(pi->cmds[i]);
1959 if (command->argv) {
1960 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001961 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001962 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001963
1964 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001965 pipefds[0] = 0;
1966 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001967 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001968 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001969
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001970 command->pid = BB_MMU ? fork() : vfork();
1971 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00001972 if (ENABLE_HUSH_JOB)
1973 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001974#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001975 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00001976 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001977 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001978 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001979 /* Don't do pgrp restore anymore on fatal signals */
1980 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001981 pgrp = pi->pgrp;
1982 if (pgrp < 0) /* true for 1st process only */
1983 pgrp = getpid();
1984 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001985 /* We do it in *every* child, not just first,
1986 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001987 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001988 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001989 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001990#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00001991 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001992 xmove_fd(pipefds[1], 1); /* write end */
1993 if (pipefds[0] > 1)
1994 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00001995 /* Like bash, explicit redirects override pipes,
1996 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001997 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001998
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001999 /* Restore default handlers just prior to exec */
2000 set_jobctrl_sighandler(SIG_DFL);
2001 set_misc_sighandler(SIG_DFL);
2002 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002003 /* Stores to nommu_save list of env vars putenv'ed
2004 * (NOMMU, on MMU we don't need that) */
2005 /* cast away volatility... */
2006 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002007 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002008 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002009 /* parent */
2010#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002011 /* Clean up after vforked child */
2012 free(nommu_save.argv);
2013 free_strings_and_unsetenv(nommu_save.new_env, 1);
2014 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002015#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002016 free(argv_expanded);
2017 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002018 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002019 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002020 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002021 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002022 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002023#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002024 /* Second and next children need to know pid of first one */
2025 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002026 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002027#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002028 }
Eric Andersen25f27032001-04-26 23:22:31 +00002029
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002030 if (i)
2031 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002032 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002033 close(pipefds[1]); /* write end */
2034 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002035 nextin = pipefds[0];
2036 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002037
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002038 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002039 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2040 return 1;
2041 }
2042
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002043 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002044 return -1;
2045}
2046
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002047#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002048static void debug_print_tree(struct pipe *pi, int lvl)
2049{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002050 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002051 [PIPE_SEQ] = "SEQ",
2052 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002053 [PIPE_OR ] = "OR" ,
2054 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002055 };
2056 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002057 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002058#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002059 [RES_IF ] = "IF" ,
2060 [RES_THEN ] = "THEN" ,
2061 [RES_ELIF ] = "ELIF" ,
2062 [RES_ELSE ] = "ELSE" ,
2063 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002064#endif
2065#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002066 [RES_FOR ] = "FOR" ,
2067 [RES_WHILE] = "WHILE",
2068 [RES_UNTIL] = "UNTIL",
2069 [RES_DO ] = "DO" ,
2070 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002071#endif
2072#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002073 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002074#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002075#if ENABLE_HUSH_CASE
2076 [RES_CASE ] = "CASE" ,
2077 [RES_MATCH] = "MATCH",
2078 [RES_CASEI] = "CASEI",
2079 [RES_ESAC ] = "ESAC" ,
2080#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002081 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002082 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002083 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002084 static const char *const GRPTYPE[] = {
2085 "()",
2086 "{}",
2087#if ENABLE_HUSH_FUNCTIONS
2088 "func()",
2089#endif
2090 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002091
2092 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002093
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002094 pin = 0;
2095 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002096 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2097 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002098 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002099 while (prn < pi->num_cmds) {
2100 struct command *command = &pi->cmds[prn];
2101 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002102
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002103 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2104 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002105 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002106 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002107 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002108 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002109 prn++;
2110 continue;
2111 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002112 if (argv) while (*argv) {
2113 fprintf(stderr, " '%s'", *argv);
2114 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002115 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002116 fprintf(stderr, "\n");
2117 prn++;
2118 }
2119 pi = pi->next;
2120 pin++;
2121 }
2122}
2123#endif
2124
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002125/* NB: called by pseudo_exec, and therefore must not modify any
2126 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002127static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002128{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002129#if ENABLE_HUSH_CASE
2130 char *case_word = NULL;
2131#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002132#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002133 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002134 char *for_varname = NULL;
2135 char **for_lcur = NULL;
2136 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002137#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002138 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002139 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002140#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002141 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002142#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002143 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002144#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002145 /*enum reserved_style*/ smallint rword = RES_NONE;
2146 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002147
Denis Vlasenko87a86552008-07-29 19:43:10 +00002148 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002149
Denis Vlasenko06810332007-05-21 23:30:54 +00002150#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002151 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002152 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2153 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002154 continue;
2155 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002156 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002157 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002158 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002159 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002160 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002161 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002162 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002163 continue;
2164 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002165 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2166 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002167 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002168 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002169 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002170 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002171 }
2172 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002173#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002174
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002175 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002176 * in order to return, no direct "return" statements please.
2177 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002178
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002179#if ENABLE_HUSH_JOB
2180 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2181 * We are saving state before entering outermost list ("while...done")
2182 * so that ctrl-Z will correctly background _entire_ outermost list,
2183 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002184 if (++G.run_list_level == 1 && G.interactive_fd) {
2185 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002186 /* ctrl-Z forked and we are parent; or ctrl-C.
2187 * Sighandler has longjmped us here */
2188 signal(SIGINT, SIG_IGN);
2189 signal(SIGTSTP, SIG_IGN);
2190 /* Restore level (we can be coming from deep inside
2191 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002192 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002193#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002194 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002195 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002196 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002197 }
2198#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002199 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002200 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2201 * Remember this child as background job */
2202 insert_bg_job(pi);
2203 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002204 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002205 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002206 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002207 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002208 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002209 rcode = 0;
2210 goto ret;
2211 }
2212 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002213 G.toplevel_list = pi;
2214 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002215#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002216 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002217#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002218 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002219 signal(SIGINT, handler_ctrl_c);
2220 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002221#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002222
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002223 /* Go through list of pipes, (maybe) executing them. */
2224 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002225 IF_HAS_KEYWORDS(rword = pi->res_word;)
2226 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002227 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2228 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002229#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002230 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002231 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002232 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002233 /* start of a loop: remember where loop starts */
2234 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002235 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002236 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002237#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002238 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002239 if (pi->followup == PIPE_SEQ)
2240 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002241 /* it is "<false> && CMD" or "<true> || CMD"
2242 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002243 continue;
2244 }
2245 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002246 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002247#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002248 if (cond_code) {
2249 if (rword == RES_THEN) {
2250 /* "if <false> THEN cmd": skip cmd */
2251 continue;
2252 }
2253 } else {
2254 if (rword == RES_ELSE || rword == RES_ELIF) {
2255 /* "if <true> then ... ELSE/ELIF cmd":
2256 * skip cmd and all following ones */
2257 break;
2258 }
2259 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002260#endif
2261#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002262 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002263 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002264 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002265
2266 static const char encoded_dollar_at[] ALIGN1 = {
2267 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2268 }; /* encoded representation of "$@" */
2269 static const char *const encoded_dollar_at_argv[] = {
2270 encoded_dollar_at, NULL
2271 }; /* argv list with one element: "$@" */
2272 char **vals;
2273
2274 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002275 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002276 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002277 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002278 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002279 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002280 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002281 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002282 debug_print_strings("for_list made from", vals);
2283 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002284 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002285 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002286 for_varname = pi->cmds[0].argv[0];
2287 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002288 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002289 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002290 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002291 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002292 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002293 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002294 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002295 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002296 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002297 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002298 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002299//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002300 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2301 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002302 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002303 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002304 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002305 if (rword == RES_DONE) {
2306 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002307 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002308#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002309#if ENABLE_HUSH_CASE
2310 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002311 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002312 continue;
2313 }
2314 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002315 char **argv;
2316
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002317 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2318 break;
2319 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002320 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002321 while (*argv) {
2322 char *pattern = expand_string_to_string(*argv);
2323 /* TODO: which FNM_xxx flags to use? */
2324 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2325 free(pattern);
2326 if (cond_code == 0) { /* match! we will execute this branch */
2327 free(case_word); /* make future "word)" stop */
2328 case_word = NULL;
2329 break;
2330 }
2331 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002332 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002333 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002334 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002335 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002336 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002337 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002338 }
2339#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002340 if (pi->num_cmds == 0)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002341 continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002342
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002343 /* After analyzing all keywords and conditions, we decided
2344 * to execute this pipe. NB: has to do checkjobs(NULL)
2345 * after run_pipe() to collect any background children,
2346 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002347 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002348 {
2349 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002350#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002351 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002352#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002353 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2354 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002355 /* we only ran a builtin: rcode is already known
2356 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002357#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002358 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002359 if (G.flag_break_continue) {
2360 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002361 /* we might fall into outer *loop*,
2362 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002363 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002364 G.depth_break_continue--;
2365 if (G.depth_break_continue == 0)
2366 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002367 /* else: e.g. "continue 2" should *break* once, *then* continue */
2368 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002369 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002370 goto check_jobs_and_break;
2371 /* "continue": simulate end of loop */
2372 rword = RES_DONE;
2373 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002374 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002375#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002376 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002377 /* what does bash do with attempts to background builtins? */
2378 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002379 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2380 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002381#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002382 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002383 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002384#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002385 rcode = 0; /* EXIT_SUCCESS */
2386 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002387#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002388 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002389 /* waits for completion, then fg's main shell */
2390 rcode = checkjobs_and_fg_shell(pi);
2391 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2392 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002393#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002394 { /* this one just waits for completion */
2395 rcode = checkjobs(pi);
2396 debug_printf_exec(": checkjobs returned %d\n", rcode);
2397 }
Eric Andersen25f27032001-04-26 23:22:31 +00002398 }
2399 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002400 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002401 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002402
2403 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002404#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002405 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002406 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002407#endif
2408#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002409 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002410 if (rcode) {
2411 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002412 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002413 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002414 }
2415 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002416 if (!rcode) {
2417 check_jobs_and_break:
2418 checkjobs(NULL);
2419 break;
2420 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002421 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002422#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002423 if ((rcode == 0 && pi->followup == PIPE_OR)
2424 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002425 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002426 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002427 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002428 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002429 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002430
2431#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002432 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002433 /* ctrl-Z forked somewhere in the past, we are the child,
2434 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002435//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002436 exit(rcode);
2437 }
2438 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002439 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002440 signal(SIGTSTP, SIG_IGN);
2441 signal(SIGINT, SIG_IGN);
2442 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002443#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002444 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002445#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002446 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002447 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002448 free(for_list);
2449#endif
2450#if ENABLE_HUSH_CASE
2451 free(case_word);
2452#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002453 return rcode;
2454}
2455
Eric Andersen25f27032001-04-26 23:22:31 +00002456/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002457static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002458{
2459 char **p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002460 struct command *command;
Eric Andersen25f27032001-04-26 23:22:31 +00002461 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002462 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002463
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002464 if (pi->stopped_cmds > 0)
Eric Andersen52a97ca2001-06-22 06:49:26 +00002465 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002466 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002467 for (i = 0; i < pi->num_cmds; i++) {
2468 command = &pi->cmds[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002469 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002470 if (command->argv) {
2471 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002472 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002473 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002474 free_strings(command->argv);
2475 command->argv = NULL;
2476 } else if (command->group) {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002477 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002478 ret_code = free_pipe_list(command->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002479 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002480 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002481 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002482 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002483 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko211b59b2008-06-23 16:28:53 +00002484 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002485 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002486 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002487 if (r->rd_filename) {
2488 debug_printf_clean(" %s\n", r->rd_filename);
2489 free(r->rd_filename);
2490 r->rd_filename = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002491 }
Eric Andersen25f27032001-04-26 23:22:31 +00002492 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002493 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002494 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002495 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002496 free(r);
2497 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002498 command->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002499 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002500 free(pi->cmds); /* children are an array, they get freed all at once */
2501 pi->cmds = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002502#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002503 free(pi->cmdtext);
2504 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002505#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002506 return ret_code;
2507}
2508
Eric Andersenbf7df042001-05-23 22:18:35 +00002509static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002510{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002511 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002512 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002513
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002514 for (pi = head; pi; pi = next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002515#if HAS_KEYWORDS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002516 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002517#endif
Eric Andersenbf7df042001-05-23 22:18:35 +00002518 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002519 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002520 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002521 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002522 free(pi);
2523 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002524 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002525}
2526
2527/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002528static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002529{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002530 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002531 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002532 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002533 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002534 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002535 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002536 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002537 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002538 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002539 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002540 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002541 return rcode;
2542}
2543
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002544
Denis Vlasenko170435c2007-05-23 13:01:10 +00002545/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002546 * all variable references within and returns a pointer to
2547 * a list of expanded strings, possibly with larger number
2548 * of strings. (Think VAR="a b"; echo $VAR).
2549 * This new list is allocated as a single malloc block.
2550 * NULL-terminated list of char* pointers is at the beginning of it,
2551 * followed by strings themself.
2552 * Caller can deallocate entire list by single free(list). */
2553
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002554/* Store given string, finalizing the word and starting new one whenever
Denis Vlasenko87a86552008-07-29 19:43:10 +00002555 * we encounter IFS char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002556 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002557static int expand_on_ifs(o_string *output, int n, const char *str)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002558{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002559 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002560 int word_len = strcspn(str, G.ifs);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002561 if (word_len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002562 if (output->o_quote || !output->o_glob)
2563 o_addQstr(output, str, word_len);
2564 else /* protect backslashes against globbing up :) */
2565 o_addstr_duplicate_backslash(output, str, word_len);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002566 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002567 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002568 if (!*str) /* EOL - do not finalize word */
2569 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002570 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002571 debug_print_list("expand_on_ifs", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002572 n = o_save_ptr(output, n);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002573 str += strspn(str, G.ifs); /* skip ifs chars */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002574 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002575 debug_print_list("expand_on_ifs[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002576 return n;
2577}
2578
2579/* Expand all variable references in given string, adding words to list[]
2580 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2581 * to be filled). This routine is extremely tricky: has to deal with
2582 * variables/parameters with whitespace, $* and $@, and constructs like
2583 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002584static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002585{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002586 /* or_mask is either 0 (normal case) or 0x80
Denis Vlasenko55789c62008-06-18 16:30:42 +00002587 * (expansion of right-hand side of assignment == 1-element expand.
2588 * It will also do no globbing, and thus we must not backslash-quote!) */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002589
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002590 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002591 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002592 const char *val;
2593 char *p;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002594
2595 ored_ch = 0;
2596
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002597 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002598 debug_print_list("expand_vars_to_list", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002599 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002600 debug_print_list("expand_vars_to_list[0]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002601
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002602 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002603#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002604 o_string subst_result = NULL_O_STRING;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002605#endif
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002606 o_addstr(output, arg, p - arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002607 debug_print_list("expand_vars_to_list[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002608 arg = ++p;
2609 p = strchr(p, SPECIAL_VAR_SYMBOL);
2610
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002611 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002612 /* "$@" is special. Even if quoted, it can still
2613 * expand to nothing (not even an empty string) */
2614 if ((first_ch & 0x7f) != '@')
2615 ored_ch |= first_ch;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002616 val = NULL;
2617 switch (first_ch & 0x7f) {
2618 /* Highest bit in first_ch indicates that var is double-quoted */
2619 case '$': /* pid */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002620 val = utoa(G.root_pid);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002621 break;
2622 case '!': /* bg pid */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002623 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002624 break;
2625 case '?': /* exitcode */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002626 val = utoa(G.last_return_code);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002627 break;
2628 case '#': /* argc */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002629 val = utoa(G.global_argc ? G.global_argc-1 : 0);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002630 break;
2631 case '*':
2632 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002633 i = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002634 if (!G.global_argv[i])
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002635 break;
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002636 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002637 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002638 smallint sv = output->o_quote;
2639 /* unquoted var's contents should be globbed, so don't quote */
2640 output->o_quote = 0;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002641 while (G.global_argv[i]) {
2642 n = expand_on_ifs(output, n, G.global_argv[i]);
2643 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2644 if (G.global_argv[i++][0] && G.global_argv[i]) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002645 /* this argv[] is not empty and not last:
2646 * put terminating NUL, start new word */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002647 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002648 debug_print_list("expand_vars_to_list[2]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002649 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002650 debug_print_list("expand_vars_to_list[3]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002651 }
2652 }
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002653 output->o_quote = sv;
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002654 } else
2655 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002656 * and in this case should treat it like '$*' - see 'else...' below */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002657 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002658 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002659 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2660 if (++i >= G.global_argc)
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002661 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002662 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002663 debug_print_list("expand_vars_to_list[4]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002664 n = o_save_ptr(output, n);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002665 }
2666 } else { /* quoted $*: add as one word */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002667 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002668 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2669 if (!G.global_argv[++i])
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002670 break;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002671 if (G.ifs[0])
2672 o_addchr(output, G.ifs[0]);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002673 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002674 }
2675 break;
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002676 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2677 /* "Empty variable", used to make "" etc to not disappear */
2678 arg++;
2679 ored_ch = 0x80;
2680 break;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002681#if ENABLE_HUSH_TICK
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002682 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002683 struct in_str input;
2684 *p = '\0';
2685 arg++;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002686//TODO: can we just stuff it into "output" directly?
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002687 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002688 setup_string_in_str(&input, arg);
2689 process_command_subs(&subst_result, &input, NULL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002690 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002691 val = subst_result.data;
2692 goto store_val;
2693 }
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002694#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002695 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002696 *p = '\0';
2697 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002698 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002699 i = xatoi_u(arg);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002700 if (i < G.global_argc)
2701 val = G.global_argv[i];
Denis Vlasenko55789c62008-06-18 16:30:42 +00002702 /* else val remains NULL: $N with too big N */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002703 } else
2704 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002705 arg[0] = first_ch;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002706#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002707 store_val:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002708#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002709 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002710 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002711 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002712 if (val) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002713 /* unquoted var's contents should be globbed, so don't quote */
2714 smallint sv = output->o_quote;
2715 output->o_quote = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002716 n = expand_on_ifs(output, n, val);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002717 val = NULL;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002718 output->o_quote = sv;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002719 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002720 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002721 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002722 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002723 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002724 if (val) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002725 o_addQstr(output, val, strlen(val));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002726 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002727
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002728#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002729 o_free(&subst_result);
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002730#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002731 arg = ++p;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002732 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2733
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002734 if (arg[0]) {
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002735 debug_print_list("expand_vars_to_list[a]", output, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002736 /* this part is literal, and it was already pre-quoted
2737 * if needed (much earlier), do not use o_addQstr here! */
2738 o_addstr(output, arg, strlen(arg) + 1);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002739 debug_print_list("expand_vars_to_list[b]", output, n);
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002740 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2741 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2742 ) {
2743 n--;
2744 /* allow to reuse list[n] later without re-growth */
2745 output->has_empty_slot = 1;
2746 } else {
2747 o_addchr(output, '\0');
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002748 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002749 return n;
2750}
2751
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002752static char **expand_variables(char **argv, int or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002753{
2754 int n;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002755 char **list;
2756 char **v;
2757 o_string output = NULL_O_STRING;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002758
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002759 if (or_mask & 0x100) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002760 output.o_quote = 1; /* protect against globbing for "$var" */
2761 /* (unquoted $var will temporarily switch it off) */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002762 output.o_glob = 1;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002763 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002764
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002765 n = 0;
2766 v = argv;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002767 while (*v) {
2768 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2769 v++;
2770 }
2771 debug_print_list("expand_variables", &output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002772
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002773 /* output.data (malloced in one block) gets returned in "list" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002774 list = o_finalize_list(&output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002775 debug_print_strings("expand_variables[1]", list);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002776 return list;
2777}
2778
Denis Vlasenko170435c2007-05-23 13:01:10 +00002779static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002780{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002781 return expand_variables(argv, 0x100);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002782}
2783
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002784/* Used for expansion of right hand of assignments */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002785/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2786 * "v=/bin/c*" */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002787static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002788{
2789 char *argv[2], **list;
2790
2791 argv[0] = (char*)str;
2792 argv[1] = NULL;
2793 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002794 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002795 if (!list[0] || list[1])
2796 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002797 /* actually, just move string 2*sizeof(char*) bytes back */
2798 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002799 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2800 return (char*)list;
2801}
2802
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002803/* Used for "eval" builtin */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002804static char* expand_strvec_to_string(char **argv)
2805{
2806 char **list;
2807
2808 list = expand_variables(argv, 0x80);
2809 /* Convert all NULs to spaces */
2810 if (list[0]) {
2811 int n = 1;
2812 while (list[n]) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002813 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002814 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2815 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002816 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002817 n++;
2818 }
2819 }
2820 strcpy((char*)list, list[0]);
2821 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002822 return (char*)list;
2823}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002824
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002825
2826/* Used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002827static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002828{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002829 struct variable *cur;
2830 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002831
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002832 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002833 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002834 len = strlen(name);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002835 for (cur = G.top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002836 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002837 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002838 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002839 return NULL;
2840}
2841
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002842/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002843 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002844static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002845{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002846 struct variable *cur;
2847 char *value;
2848 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002849
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002850 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002851 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002852 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002853 return -1;
2854 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002855
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002856 name_len = value - str + 1; /* including '=' */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002857 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002858 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002859 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002860 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002861 /* Bail out. Note that now cur points
2862 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002863 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002864 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002865 cur = cur->next;
2866 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002867 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002868 /* We found an existing var with this name */
2869 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002870 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002871 bb_error_msg("%s: readonly variable", str);
2872 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002873 return -1;
2874 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002875 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002876 unsetenv(str); /* just in case */
2877 *value = '=';
2878 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002879 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002880 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002881 goto exp;
2882 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002883 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002884 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002885 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002886 goto free_and_exp;
2887 }
2888 /* max_len == 0 signifies "malloced" var, which we can
2889 * (and has to) free */
2890 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002891 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002892 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002893 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002894 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002895
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002896 /* Not found - create next variable struct */
2897 cur->next = xzalloc(sizeof(*cur));
2898 cur = cur->next;
2899
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002900 set_str_and_exp:
2901 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002902 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002903 if (flg_export)
2904 cur->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002905 if (cur->flg_export) {
2906 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002907 return putenv(cur->varstr);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002908 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002909 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002910}
2911
Eric Andersenf72f5622001-05-15 23:21:41 +00002912static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002913{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002914 struct variable *cur;
2915 struct variable *prev = prev; /* for gcc */
2916 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002917
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002918 if (!name)
2919 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002920 name_len = strlen(name);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002921 cur = G.top_var;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002922 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002923 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002924 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002925 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002926 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002927 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002928 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2929 * is ro, and we cannot reach this code on the 1st pass */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002930 prev->next = cur->next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002931 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +00002932 bb_unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002933 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002934 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002935 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002936 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002937 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002938 prev = cur;
2939 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002940 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002941}
2942
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002943/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00002944 * for file descriptor duplication, e.g., "2>&1".
2945 * Return code is 0 normally, 1 if a syntax error is detected in src.
2946 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002947static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00002948 struct in_str *input)
2949{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002950 struct command *command = ctx->command;
2951 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002952 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002953
2954 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002955 while (redir) {
2956 last_redir = redir;
2957 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002958 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002959 redir = xzalloc(sizeof(struct redir_struct));
2960 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002961 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002962 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002963 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002964 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002965 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002966 }
2967
Denis Vlasenko55789c62008-06-18 16:30:42 +00002968 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002969 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002970
2971 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2972
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002973 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002974 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002975 if (redir->dup == -2)
2976 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002977 if (redir->dup != -1) {
2978 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002979 * is legit; I postpone that to "run time"
2980 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002981 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2982 } else {
2983 /* We do _not_ try to open the file that src points to,
2984 * since we need to return and let src be expanded first.
2985 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002986 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002987 ctx->pending_redirect = redir;
2988 }
2989 return 0;
2990}
2991
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002992static struct pipe *new_pipe(void)
2993{
Eric Andersen25f27032001-04-26 23:22:31 +00002994 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002995 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002996 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002997 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002998 return pi;
2999}
3000
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003001static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003002{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003003 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003004 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003005 /* Create the memory for command, roughly:
3006 * ctx->pipe->cmds = new struct command;
3007 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003008 */
3009 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003010}
3011
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003012/* If a reserved word is found and processed, parse context is modified
3013 * and 1 is returned.
3014 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003015 * case, function, and select are obnoxious, save those for later.
3016 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003017#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003018struct reserved_combo {
3019 char literal[6];
3020 unsigned char res;
3021 unsigned char assignment_flag;
3022 int flag;
3023};
3024enum {
3025 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003026#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003027 FLAG_IF = (1 << RES_IF ),
3028 FLAG_THEN = (1 << RES_THEN ),
3029 FLAG_ELIF = (1 << RES_ELIF ),
3030 FLAG_ELSE = (1 << RES_ELSE ),
3031 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003032#endif
3033#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003034 FLAG_FOR = (1 << RES_FOR ),
3035 FLAG_WHILE = (1 << RES_WHILE),
3036 FLAG_UNTIL = (1 << RES_UNTIL),
3037 FLAG_DO = (1 << RES_DO ),
3038 FLAG_DONE = (1 << RES_DONE ),
3039 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003040#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003041#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003042 FLAG_MATCH = (1 << RES_MATCH),
3043 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003044#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003045 FLAG_START = (1 << RES_XXXX ),
3046};
3047
3048static const struct reserved_combo* match_reserved_word(o_string *word)
3049{
Eric Andersen25f27032001-04-26 23:22:31 +00003050 /* Mostly a list of accepted follow-up reserved words.
3051 * FLAG_END means we are done with the sequence, and are ready
3052 * to turn the compound list into a command.
3053 * FLAG_START means the word must start a new compound list.
3054 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003055 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003056#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003057 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3058 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3059 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3060 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3061 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3062 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003063#endif
3064#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003065 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3066 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3067 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3068 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3069 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3070 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003071#endif
3072#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003073 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3074 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003075#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003076 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003077 const struct reserved_combo *r;
3078
3079 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3080 if (strcmp(word->data, r->literal) == 0)
3081 return r;
3082 }
3083 return NULL;
3084}
3085static int reserved_word(o_string *word, struct parse_context *ctx)
3086{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003087#if ENABLE_HUSH_CASE
3088 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003089 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003090 };
3091#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003092 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003093
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003094 r = match_reserved_word(word);
3095 if (!r)
3096 return 0;
3097
3098 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003099#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003100 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3101 /* "case word IN ..." - IN part starts first match part */
3102 r = &reserved_match;
3103 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003104#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003105 if (r->flag == 0) { /* '!' */
3106 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003107 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003108 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003109 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003110 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003111 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003112 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003113 if (r->flag & FLAG_START) {
3114 struct parse_context *new;
3115 debug_printf("push stack\n");
3116 new = xmalloc(sizeof(*new));
3117 *new = *ctx; /* physical copy */
3118 initialize_context(ctx);
3119 ctx->stack = new;
3120 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3121 syntax(NULL);
3122 ctx->ctx_res_w = RES_SNTX;
3123 return 1;
3124 }
3125 ctx->ctx_res_w = r->res;
3126 ctx->old_flag = r->flag;
3127 if (ctx->old_flag & FLAG_END) {
3128 struct parse_context *old;
3129 debug_printf("pop stack\n");
3130 done_pipe(ctx, PIPE_SEQ);
3131 old = ctx->stack;
3132 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003133 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003134 *ctx = *old; /* physical copy */
3135 free(old);
3136 }
3137 word->o_assignment = r->assignment_flag;
3138 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003139}
Denis Vlasenko06810332007-05-21 23:30:54 +00003140#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003141
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003142//TODO: many, many callers don't check error from done_word()
3143
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003144/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003145 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003146static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003147{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003148 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003149
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003150 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003151 if (word->length == 0 && word->nonnull == 0) {
3152 debug_printf_parse("done_word return 0: true null, ignored\n");
3153 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003154 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003155 /* If this word wasn't an assignment, next ones definitely
3156 * can't be assignments. Even if they look like ones. */
3157 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3158 && word->o_assignment != WORD_IS_KEYWORD
3159 ) {
3160 word->o_assignment = NOT_ASSIGNMENT;
3161 } else {
3162 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003163 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003164 word->o_assignment = MAYBE_ASSIGNMENT;
3165 }
3166
Eric Andersen25f27032001-04-26 23:22:31 +00003167 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003168 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3169 * only if run as "bash", not "sh" */
3170 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003171 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003172 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003173 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003174 /* "{ echo foo; } echo bar" - bad */
3175 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003176 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003177 syntax(NULL);
3178 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3179 return 1;
3180 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003181#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003182#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003183 if (ctx->ctx_dsemicolon
3184 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3185 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003186 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003187 /* ctx->ctx_res_w = RES_MATCH; */
3188 ctx->ctx_dsemicolon = 0;
3189 } else
3190#endif
3191
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003192 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003193#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003194 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3195 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003196#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003197 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003198 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3199 if (reserved_word(word, ctx)) {
3200 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003201 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3202 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003203 }
Eric Andersen25f27032001-04-26 23:22:31 +00003204 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003205#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003206 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003207 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3208 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003209 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003210 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003211 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003212 char *p = word->data;
3213 while (p[0] == SPECIAL_VAR_SYMBOL
3214 && (p[1] & 0x7f) == '@'
3215 && p[2] == SPECIAL_VAR_SYMBOL
3216 ) {
3217 p += 3;
3218 }
3219 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003220 /* saw no "$@", or not only "$@" but some
3221 * real text is there too */
3222 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003223 * e.g. "", $empty"" etc to not disappear */
3224 o_addchr(word, SPECIAL_VAR_SYMBOL);
3225 o_addchr(word, SPECIAL_VAR_SYMBOL);
3226 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003227 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003228 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003229 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003230 }
Eric Andersen25f27032001-04-26 23:22:31 +00003231
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003232 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003233 ctx->pending_redirect = NULL;
3234
Denis Vlasenko06810332007-05-21 23:30:54 +00003235#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003236 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003237 /* NB: basically, this makes hush see "for v in ..." syntax as if
3238 * as it is "for v; in ...". FOR and IN become two pipe structs
3239 * in parse tree. */
3240 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003241//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003242 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003243 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003244#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003245#if ENABLE_HUSH_CASE
3246 /* Force CASE to have just one word */
3247 if (ctx->ctx_res_w == RES_CASE) {
3248 done_pipe(ctx, PIPE_SEQ);
3249 }
3250#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003251 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003252 return 0;
3253}
3254
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003255/* Command (member of a pipe) is complete. The only possible error here
3256 * is out of memory, in which case xmalloc exits. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003257static int done_command(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003258{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003259 /* The command is really already in the pipe structure, so
3260 * advance the pipe counter and make a new, null command. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003261 struct pipe *pi = ctx->pipe;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003262 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003263
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003264 if (command) {
3265 if (command->group == NULL
3266 && command->argv == NULL
3267 && command->redirects == NULL
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003268 ) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003269 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3270 return pi->num_cmds;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003271 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003272 pi->num_cmds++;
3273 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003274 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003275 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003276 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003277
3278 /* Only real trickiness here is that the uncommitted
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003279 * command structure is not counted in pi->num_cmds. */
3280 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3281 command = &pi->cmds[pi->num_cmds];
3282 memset(command, 0, sizeof(*command));
Eric Andersen25f27032001-04-26 23:22:31 +00003283
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003284 ctx->command = command;
Eric Andersen25f27032001-04-26 23:22:31 +00003285 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003286
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003287 return pi->num_cmds; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003288}
3289
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003290static void done_pipe(struct parse_context *ctx, pipe_style type)
Eric Andersen25f27032001-04-26 23:22:31 +00003291{
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003292 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003293
3294 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenko395ae452008-07-14 06:29:38 +00003295 /* Close previous command */
3296 not_null = done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003297 ctx->pipe->followup = type;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003298 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3299 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003300 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
Denis Vlasenko395ae452008-07-14 06:29:38 +00003301
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003302 /* Without this check, even just <enter> on command line generates
3303 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003304 * IOW: it is safe to do it unconditionally.
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003305 * RES_NONE case is for "for a in; do ..." (empty IN set)
3306 * to work, possibly other cases too. */
3307 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003308 struct pipe *new_p;
3309 debug_printf_parse("done_pipe: adding new pipe: "
Denis Vlasenko757361f2008-07-14 08:26:47 +00003310 "not_null:%d ctx->ctx_res_w:%d\n",
Denis Vlasenko395ae452008-07-14 06:29:38 +00003311 not_null, ctx->ctx_res_w);
3312 new_p = new_pipe();
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003313 ctx->pipe->next = new_p;
3314 ctx->pipe = new_p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003315 ctx->command = NULL; /* needed! */
Denis Vlasenko395ae452008-07-14 06:29:38 +00003316 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003317 * they remain set for commands inside if/while.
3318 * This is used to control execution.
3319 * RES_FOR and RES_IN are NOT sticky (needed to support
3320 * cases where variable or value happens to match a keyword):
3321 */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003322#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003323 if (ctx->ctx_res_w == RES_FOR
3324 || ctx->ctx_res_w == RES_IN)
3325 ctx->ctx_res_w = RES_NONE;
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003326#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003327#if ENABLE_HUSH_CASE
3328 if (ctx->ctx_res_w == RES_MATCH)
3329 ctx->ctx_res_w = RES_CASEI;
3330#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003331 /* Create the memory for command, roughly:
3332 * ctx->pipe->cmds = new struct command;
3333 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003334 */
3335 done_command(ctx);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003336 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003337 debug_printf_parse("done_pipe return\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003338}
3339
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003340/* Peek ahead in the in_str to find out if we have a "&n" construct,
Eric Andersen25f27032001-04-26 23:22:31 +00003341 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003342 * Return either -2 (syntax error), -1 (no &), or the number found.
Eric Andersen25f27032001-04-26 23:22:31 +00003343 */
3344static int redirect_dup_num(struct in_str *input)
3345{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003346 int ch, d = 0, ok = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003347 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003348 if (ch != '&') return -1;
3349
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003350 i_getch(input); /* get the & */
3351 ch = i_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003352 if (ch == '-') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003353 i_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003354 return -3; /* "-" represents "close me" */
3355 }
3356 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003357 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003358 ok = 1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003359 i_getch(input);
3360 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003361 }
3362 if (ok) return d;
3363
Manuel Novoa III cad53642003-03-19 09:13:01 +00003364 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003365 return -2;
3366}
3367
3368/* If a redirect is immediately preceded by a number, that number is
3369 * supposed to tell which file descriptor to redirect. This routine
3370 * looks for such preceding numbers. In an ideal world this routine
3371 * needs to handle all the following classes of redirects...
3372 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3373 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3374 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3375 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3376 * A -1 output from this program means no valid number was found, so the
3377 * caller should use the appropriate default for this redirection.
3378 */
3379static int redirect_opt_num(o_string *o)
3380{
3381 int num;
3382
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003383 if (o->length == 0)
3384 return -1;
3385 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003386 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003387 return -1;
3388 }
3389 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003390 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003391 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003392 return num;
3393}
3394
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003395#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003396static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003397{
3398 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003399 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003400
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003401 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003402/* *** NOMMU WARNING *** */
3403/* By using vfork here, we suspend parent till child exits or execs.
3404 * If child will not do it before it fills the pipe, it can block forever
3405 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003406 * Try this script:
3407 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3408 * huge=`cat TESTFILE` # will block here forever
3409 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003410 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003411 pid = BB_MMU ? fork() : vfork();
3412 if (pid < 0)
3413 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003414 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003415 if (ENABLE_HUSH_JOB)
3416 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003417 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003418 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003419 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003420#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003421 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003422#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003423 /* Process substitution is not considered to be usual
3424 * 'command execution'.
3425 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3426 /* Not needed, we are relying on it being disabled
3427 * everywhere outside actual command execution. */
3428 /*set_jobctrl_sighandler(SIG_IGN);*/
3429 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003430 /* Freeing 'head' here would break NOMMU. */
3431 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003432 }
Eric Andersen25f27032001-04-26 23:22:31 +00003433 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003434 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003435 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003436 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003437}
3438
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003439/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003440static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003441 struct in_str *input,
3442 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003443{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003444 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003445 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003446 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003447 FILE *p;
3448 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003449
Eric Andersen25f27032001-04-26 23:22:31 +00003450 initialize_context(&inner);
3451
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003452 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003453 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003454 if (retcode != 0)
3455 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003456 done_word(&result, &inner);
3457 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003458 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003459
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003460 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003461 if (p == NULL)
3462 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003463 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003464 setup_file_in_str(&pipe_str, p);
3465
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003466 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003467 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003468 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003469 if (ch == '\n') {
3470 eol_cnt++;
3471 continue;
3472 }
3473 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003474 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003475 eol_cnt--;
3476 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003477 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003478 }
3479
3480 debug_printf("done reading from pipe, pclose()ing\n");
3481 /* This is the step that wait()s for the child. Should be pretty
3482 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003483 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003484 * at the same time. That would be a lot of work, and contrary
3485 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003486 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003487 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003488 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003489 return retcode;
3490}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003491#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003492
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003493static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003494 struct in_str *input, int ch)
3495{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003496 /* dest contains characters seen prior to ( or {.
3497 * Typically it's empty, but for functions defs,
3498 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003499 int rcode;
3500 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003501 struct parse_context sub;
3502 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003503
3504 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003505#if ENABLE_HUSH_FUNCTIONS
3506 if (ch == 'F') { /* function definition? */
3507 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3508 //command->fname = dest->data;
3509 command->grp_type = GRP_FUNCTION;
3510//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3511 memset(dest, 0, sizeof(*dest));
3512 }
3513#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003514 if (command->argv /* word [word](... */
3515 || dest->length /* word(... */
3516 || dest->nonnull /* ""(... */
3517 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003518 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003519 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3520 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003521 }
3522 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003523 endch = "}";
3524 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003525 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003526 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003527 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003528 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003529 if (rcode == 0) {
3530 done_word(dest, &sub); /* finish off the final word in the subcontext */
3531 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003532 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003533 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003534 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003535 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003536 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003537}
3538
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003539/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003540 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003541static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003542{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003543 struct variable *var = get_local_var(src);
3544 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003545 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003546 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003547}
3548
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003549#if ENABLE_HUSH_TICK
3550/* Subroutines for copying $(...) and `...` things */
3551static void add_till_backquote(o_string *dest, struct in_str *input);
3552/* '...' */
3553static void add_till_single_quote(o_string *dest, struct in_str *input)
3554{
3555 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003556 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003557 if (ch == EOF)
3558 break;
3559 if (ch == '\'')
3560 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003561 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003562 }
3563}
3564/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3565static void add_till_double_quote(o_string *dest, struct in_str *input)
3566{
3567 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003568 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003569 if (ch == '"')
3570 break;
3571 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003572 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003573 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003574 }
3575 if (ch == EOF)
3576 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003577 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003578 if (ch == '`') {
3579 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003580 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003581 continue;
3582 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003583 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003584 }
3585}
3586/* Process `cmd` - copy contents until "`" is seen. Complicated by
3587 * \` quoting.
3588 * "Within the backquoted style of command substitution, backslash
3589 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3590 * The search for the matching backquote shall be satisfied by the first
3591 * backquote found without a preceding backslash; during this search,
3592 * if a non-escaped backquote is encountered within a shell comment,
3593 * a here-document, an embedded command substitution of the $(command)
3594 * form, or a quoted string, undefined results occur. A single-quoted
3595 * or double-quoted string that begins, but does not end, within the
3596 * "`...`" sequence produces undefined results."
3597 * Example Output
3598 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3599 */
3600static void add_till_backquote(o_string *dest, struct in_str *input)
3601{
3602 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003603 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003604 if (ch == '`')
3605 break;
3606 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003607 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003608 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003609 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003610 ch = ch2;
3611 }
3612 if (ch == EOF)
3613 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003614 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003615 }
3616}
3617/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3618 * quoting and nested ()s.
3619 * "With the $(command) style of command substitution, all characters
3620 * following the open parenthesis to the matching closing parenthesis
3621 * constitute the command. Any valid shell script can be used for command,
3622 * except a script consisting solely of redirections which produces
3623 * unspecified results."
3624 * Example Output
3625 * echo $(echo '(TEST)' BEST) (TEST) BEST
3626 * echo $(echo 'TEST)' BEST) TEST) BEST
3627 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3628 */
3629static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3630{
3631 int count = 0;
3632 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003633 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003634 if (ch == EOF)
3635 break;
3636 if (ch == '(')
3637 count++;
3638 if (ch == ')')
3639 if (--count < 0)
3640 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003641 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003642 if (ch == '\'') {
3643 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003644 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003645 continue;
3646 }
3647 if (ch == '"') {
3648 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003649 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003650 continue;
3651 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003652 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3653 ch = i_getch(input);
3654 if (ch == EOF)
3655 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003656 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003657 continue;
3658 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003659 }
3660}
3661#endif /* ENABLE_HUSH_TICK */
3662
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003663/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003664static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003665{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003666 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003667 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003668
3669 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003670 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003671 i_getch(input);
3672 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003674 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003675 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003676 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003677 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003678 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003679 if (!isalnum(ch) && ch != '_')
3680 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003681 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003682 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003684 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003685 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003686 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003687 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003688 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003689 o_addchr(dest, ch | quote_mask);
3690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003691 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003692 case '$': /* pid */
3693 case '!': /* last bg pid */
3694 case '?': /* last exit code */
3695 case '#': /* number of args */
3696 case '*': /* args */
3697 case '@': /* args */
3698 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003699 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3701 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003702 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003703 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003704 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003705 if (ch == '}')
3706 break;
3707 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003708 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003709 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3710 return 1;
3711 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003712 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003713 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003714 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003715 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003716 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003717 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003718#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003719 case '(': {
3720 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003721 i_getch(input);
3722 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3723 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003724 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003725 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003727 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003728 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003729#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003730 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003731 i_getch(input);
3732 ch = i_peek(input);
3733 if (isalnum(ch)) { /* it's $_name or $_123 */
3734 ch = '_';
3735 goto make_var;
3736 }
3737 /* else: it's $_ */
3738 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003739 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003740 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003741 return 1;
3742 break;
3743 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003744 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003745 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003746 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003747 return 0;
3748}
3749
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003750/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003751 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3752 * Return code is 0 if end_trigger char is met,
3753 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003754 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003755static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003756 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003757{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003758 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003759 int redir_fd;
3760 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003761 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003762 int next;
3763
Denis Vlasenkoff097622007-10-01 10:00:45 +00003764 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003765 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003766 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003767
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003768 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 +00003769
Denis Vlasenko1a735862007-05-23 00:32:25 +00003770 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003771 m = CHAR_IFS;
3772 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003773 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003774 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003775 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003776 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003777 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003778 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003779 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003780 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003781 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003782 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003783 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003784 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003785 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003786 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003787 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3788 return 1;
3789 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003790 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003791 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3792 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003793 && ch == '='
3794 && is_assignment(dest->data)
3795 ) {
3796 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3797 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003798 continue;
3799 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003800 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003801 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003802 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003803 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003804 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003805 if (ch == EOF)
3806 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003807 /* If we aren't performing a substitution, treat
3808 * a newline as a command separator.
3809 * [why we don't handle it exactly like ';'? --vda] */
3810 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003811#if ENABLE_HUSH_CASE
3812 /* "case ... in <newline> word) ..." -
3813 * newlines are ignored (but ';' wouldn't be) */
3814 if (dest->length == 0 // && argv[0] == NULL
3815 && ctx->ctx_res_w == RES_MATCH
3816 ) {
3817 continue;
3818 }
3819#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003820 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003821 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003822 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003823 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003824 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003825 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003826 /* Special case: (...word) makes last word terminate,
3827 * as if ';' is seen */
3828 if (ch == ')') {
3829 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003830//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003831 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003832 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003833 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003834 if (!HAS_KEYWORDS
3835 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3836 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003837 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3838 return 0;
3839 }
3840 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003841 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003842 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003843 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003844
3845 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3846 /* ch is a special char and thus this word
3847 * cannot be an assignment: */
3848 dest->o_assignment = NOT_ASSIGNMENT;
3849 }
3850
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003851 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003852 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003853 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003854 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003855 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003856 if (ch == EOF || ch == '\n')
3857 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003858 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003859 }
Eric Andersen25f27032001-04-26 23:22:31 +00003860 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003861 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003862 }
3863 break;
3864 case '\\':
3865 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003866 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003867 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003868 return 1;
3869 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003870 /* bash:
3871 * "The backslash retains its special meaning [in "..."]
3872 * only when followed by one of the following characters:
3873 * $, `, ", \, or <newline>. A double quote may be quoted
3874 * within double quotes by preceding it with a backslash.
3875 * If enabled, history expansion will be performed unless
3876 * an ! appearing in double quotes is escaped using
3877 * a backslash. The backslash preceding the ! is not removed."
3878 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003879 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003880 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003881 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003882 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003883 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003884 }
3885 } else {
3886 o_addchr(dest, '\\');
3887 o_addchr(dest, i_getch(input));
3888 }
Eric Andersen25f27032001-04-26 23:22:31 +00003889 break;
3890 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003891 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003892 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3893 return 1;
3894 }
Eric Andersen25f27032001-04-26 23:22:31 +00003895 break;
3896 case '\'':
3897 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003898 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003899 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003900 if (ch == EOF) {
3901 syntax("unterminated '");
3902 debug_printf_parse("parse_stream return 1: unterminated '\n");
3903 return 1;
3904 }
3905 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003906 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003907 if (dest->o_assignment == NOT_ASSIGNMENT)
3908 o_addqchr(dest, ch);
3909 else
3910 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003911 }
Eric Andersen25f27032001-04-26 23:22:31 +00003912 break;
3913 case '"':
3914 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003915 shadow_quote ^= 1; /* invert */
3916 if (dest->o_assignment == NOT_ASSIGNMENT)
3917 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003918 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003919#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003920 case '`': {
3921 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003922 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003923 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003924 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003925 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003926 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003927 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003928 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003929#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003930 case '>':
3931 redir_fd = redirect_opt_num(dest);
3932 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003933 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003934 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003935 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003936 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003937 }
3938#if 0
3939 else if (next == '(') {
3940 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003941 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003942 return 1;
3943 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003944#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003945 setup_redirect(ctx, redir_fd, redir_style, input);
3946 break;
3947 case '<':
3948 redir_fd = redirect_opt_num(dest);
3949 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003950 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003951 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003952 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003953 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003954 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003955 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003956 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003957 }
3958#if 0
3959 else if (next == '(') {
3960 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003961 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003962 return 1;
3963 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003964#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003965 setup_redirect(ctx, redir_fd, redir_style, input);
3966 break;
3967 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003968#if ENABLE_HUSH_CASE
3969 case_semi:
3970#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003971 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003972 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003973#if ENABLE_HUSH_CASE
3974 /* Eat multiple semicolons, detect
3975 * whether it means something special */
3976 while (1) {
3977 ch = i_peek(input);
3978 if (ch != ';')
3979 break;
3980 i_getch(input);
3981 if (ctx->ctx_res_w == RES_CASEI) {
3982 ctx->ctx_dsemicolon = 1;
3983 ctx->ctx_res_w = RES_MATCH;
3984 break;
3985 }
3986 }
3987#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003988 new_cmd:
3989 /* We just finished a cmd. New one may start
3990 * with an assignment */
3991 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00003992 break;
3993 case '&':
3994 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003995 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003996 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003997 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003998 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003999 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00004000 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004001 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004002 case '|':
4003 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004004#if ENABLE_HUSH_CASE
4005 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004006 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004007#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004008 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004009 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004010 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004011 } else {
4012 /* we could pick up a file descriptor choice here
4013 * with redirect_opt_num(), but bash doesn't do it.
4014 * "echo foo 2| cat" yields "foo 2". */
4015 done_command(ctx);
4016 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004017 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004018 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004019#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004020 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004021 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004022 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004023 && dest->length == 0 /* not word(... */
4024 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004025 ) {
4026 continue;
4027 }
4028#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004029#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004030 if (dest->length != 0 /* not just () but word() */
4031 && dest->nonnull == 0 /* not a"b"c() */
4032 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004033//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004034 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004035 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004036 ) {
4037 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004038 i_getch(input);
4039 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004040//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004041 ch = i_getch(input);
4042 } while (ch == ' ' || ch == '\n');
4043 if (ch != '{') {
4044 syntax("was expecting {");
4045 debug_printf_parse("parse_stream return 1\n");
4046 return 1;
4047 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004048 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004049 }
4050#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004051 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004052 if (parse_group(dest, ctx, input, ch) != 0) {
4053 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004054 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004055 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004056 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004057 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004058#if ENABLE_HUSH_CASE
4059 if (ctx->ctx_res_w == RES_MATCH)
4060 goto case_semi;
4061#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004062 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004063 /* proper use of this character is caught by end_trigger:
4064 * if we see {, we call parse_group(..., end_trigger='}')
4065 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004066 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004067 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004068 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004069 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004070 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004071 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004072 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004073 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004074 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004075 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004076 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004077 return 0;
4078}
4079
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004080static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004081{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004082 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004083 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004084}
4085
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004086static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004087{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004088 G.ifs = getenv("IFS");
4089 if (G.ifs == NULL)
4090 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004091 /* Precompute a list of 'flow through' behavior so it can be treated
4092 * quickly up front. Computation is necessary because of IFS.
4093 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004094 * The charmap[] array only really needs two bits each,
4095 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004096 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004097 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004098#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004099 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004100#else
4101 set_in_charmap("\\$\"", CHAR_SPECIAL);
4102#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004103 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004104 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004105}
4106
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004107/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004108 * from builtin_source() and builtin_eval() */
4109static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004110{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004111 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004112 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004113 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004114
Eric Andersen25f27032001-04-26 23:22:31 +00004115 do {
4116 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004117 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004118#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004119 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004120#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004121 /* We will stop & execute after each ';' or '\n'.
4122 * Example: "sleep 9999; echo TEST" + ctrl-C:
4123 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004124 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004125 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004126#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004127 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004128 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004129 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004130#endif
4131 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004132 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004133 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004134 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004135 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4136 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004137 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004138 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004139#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004140 if (ctx.old_flag != 0) {
4141 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004142 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004143 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004144#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004145 /*temp.nonnull = 0; - o_free does it below */
4146 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004147 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004148 /* Discard all unprocessed line input, force prompt on */
4149 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004150#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004151 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004152#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004153 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004154 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004155 /* loop on syntax errors, return on EOF: */
4156 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004157 return 0;
4158}
4159
Denis Vlasenko170435c2007-05-23 13:01:10 +00004160static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004161{
4162 struct in_str input;
4163 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004164 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004165}
4166
Denis Vlasenko170435c2007-05-23 13:01:10 +00004167static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004168{
4169 int rcode;
4170 struct in_str input;
4171 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004172 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004173 return rcode;
4174}
4175
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004176#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004177/* Make sure we have a controlling tty. If we get started under a job
4178 * aware app (like bash for example), make sure we are now in charge so
4179 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004180static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004181{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004182 pid_t shell_pgrp;
4183
Denis Vlasenko87a86552008-07-29 19:43:10 +00004184 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004185 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004186
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004187 /* If we were ran as 'hush &',
4188 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004189 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004190 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004191 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004192 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004193 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004194
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004195 /* Ignore job-control and misc signals. */
4196 set_jobctrl_sighandler(SIG_IGN);
4197 set_misc_sighandler(SIG_IGN);
4198//huh? signal(SIGCHLD, SIG_IGN);
4199
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004200 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004201 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004202
4203 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004204 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004205 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004206 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004207}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004208#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004209
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004210
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004211int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004212int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004213{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004214 static const struct variable const_shell_ver = {
4215 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004216 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004217 .max_len = 1, /* 0 can provoke free(name) */
4218 .flg_export = 1,
4219 .flg_read_only = 1,
4220 };
4221
Eric Andersen25f27032001-04-26 23:22:31 +00004222 int opt;
4223 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004224 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004225 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004226
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004227 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004228
Denis Vlasenko87a86552008-07-29 19:43:10 +00004229 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004230
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004231 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004232 G.shell_ver = const_shell_ver; /* copying struct here */
4233 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004234 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004235 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4236 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004237 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004238 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004239 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004240 if (e) while (*e) {
4241 char *value = strchr(*e, '=');
4242 if (value) { /* paranoia */
4243 cur_var->next = xzalloc(sizeof(*cur_var));
4244 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004245 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004246 cur_var->max_len = strlen(*e);
4247 cur_var->flg_export = 1;
4248 }
4249 e++;
4250 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004251 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004252 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004253
Denis Vlasenko38f63192007-01-22 09:03:07 +00004254#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004255 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004256#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004257 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004258 G.global_argc = argc;
4259 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004260 /* Initialize some more globals to non-zero values */
4261 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004262#if ENABLE_HUSH_INTERACTIVE
4263#if ENABLE_FEATURE_EDITING
4264 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004265#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004266 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004267#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004268
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004269 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004270 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004271
4272 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004273 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004274 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004275 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004276 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004277 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004278 fclose(input);
4279 }
Eric Andersen25f27032001-04-26 23:22:31 +00004280 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004281 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004282
Eric Andersen25f27032001-04-26 23:22:31 +00004283 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4284 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004285 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004286 G.global_argv = argv + optind;
4287 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004288 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004289 goto final_return;
4290 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004291 /* Well, we cannot just declare interactiveness,
4292 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004293 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004294 break;
4295 case 'f':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004296 G.fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004297 break;
4298 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004299#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004300 fprintf(stderr, "Usage: sh [FILE]...\n"
4301 " or: sh -c command [args]...\n\n");
4302 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004303#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004304 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004305#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004306 }
4307 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004308#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004309 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004310 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004311 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004312 * no arguments remaining or the -s flag given
4313 * standard input is a terminal
4314 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004315 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004316 if (argv[optind] == NULL && input == stdin
4317 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4318 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004319 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4320 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4321 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004322 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004323 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4324 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004325 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004326 G.interactive_fd = dup(STDIN_FILENO);
4327 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004328 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004329 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004330 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004331 // TODO: track & disallow any attempts of user
4332 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004333 }
Eric Andersen25f27032001-04-26 23:22:31 +00004334 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004335 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4336 if (G.interactive_fd) {
4337 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004338 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004339 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004340 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004341 * (we reset die_sleep = 0 whereever we [v]fork) */
4342 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004343 if (setjmp(die_jmp)) {
4344 /* xfunc has failed! die die die */
4345 hush_exit(xfunc_error_retval);
4346 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004347#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00004348 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004349 printf("Enter 'help' for a list of built-in commands.\n\n");
4350#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004351 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004352#elif ENABLE_HUSH_INTERACTIVE
4353/* no job control compiled, only prompt/line editing */
4354 if (argv[optind] == NULL && input == stdin
4355 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4356 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004357 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4358 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004359 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004360 G.interactive_fd = dup(STDIN_FILENO);
4361 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004362 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004363 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004364 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004365 if (G.interactive_fd) {
4366 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004367 set_misc_sighandler(SIG_IGN);
4368 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004369 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004370#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004371
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004372 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004373 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004374 } else {
4375 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004376 G.global_argv = argv + optind;
4377 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004378 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004379 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004380 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004381 }
Eric Andersen25f27032001-04-26 23:22:31 +00004382
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004383 final_return:
4384
Denis Vlasenko38f63192007-01-22 09:03:07 +00004385#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004386 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004387 if (G.cwd != bb_msg_unknown)
4388 free((char*)G.cwd);
4389 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004390 while (cur_var) {
4391 struct variable *tmp = cur_var;
4392 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004393 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004394 cur_var = cur_var->next;
4395 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004396 }
Eric Andersen25f27032001-04-26 23:22:31 +00004397#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004398 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004399}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004400
4401
4402#if ENABLE_LASH
4403int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4404int lash_main(int argc, char **argv)
4405{
4406 //bb_error_msg("lash is deprecated, please use hush instead");
4407 return hush_main(argc, argv);
4408}
4409#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004410
4411
4412/*
4413 * Built-ins
4414 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004415static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004416{
4417 return 0;
4418}
4419
4420static int builtin_test(char **argv)
4421{
4422 int argc = 0;
4423 while (*argv) {
4424 argc++;
4425 argv++;
4426 }
4427 return test_main(argc, argv - argc);
4428}
4429
4430static int builtin_echo(char **argv)
4431{
4432 int argc = 0;
4433 while (*argv) {
4434 argc++;
4435 argv++;
4436 }
4437 return echo_main(argc, argv - argc);
4438}
4439
4440static int builtin_eval(char **argv)
4441{
4442 int rcode = EXIT_SUCCESS;
4443
4444 if (argv[1]) {
4445 char *str = expand_strvec_to_string(argv + 1);
4446 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4447 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004448 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004449 }
4450 return rcode;
4451}
4452
4453static int builtin_cd(char **argv)
4454{
4455 const char *newdir;
4456 if (argv[1] == NULL) {
4457 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4458 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4459 newdir = getenv("HOME") ? : "/";
4460 } else
4461 newdir = argv[1];
4462 if (chdir(newdir)) {
4463 printf("cd: %s: %s\n", newdir, strerror(errno));
4464 return EXIT_FAILURE;
4465 }
4466 set_cwd();
4467 return EXIT_SUCCESS;
4468}
4469
4470static int builtin_exec(char **argv)
4471{
4472 if (argv[1] == NULL)
4473 return EXIT_SUCCESS; /* bash does this */
4474 {
4475#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004476 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004477#endif
4478// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004479 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004480 /* never returns */
4481 }
4482}
4483
4484static int builtin_exit(char **argv)
4485{
4486// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4487 //puts("exit"); /* bash does it */
4488// TODO: warn if we have background jobs: "There are stopped jobs"
4489// On second consecutive 'exit', exit anyway.
4490 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004491 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004492 /* mimic bash: exit 123abc == exit 255 + error msg */
4493 xfunc_error_retval = 255;
4494 /* bash: exit -2 == exit 254, no error msg */
4495 hush_exit(xatoi(argv[1]) & 0xff);
4496}
4497
4498static int builtin_export(char **argv)
4499{
4500 const char *value;
4501 char *name = argv[1];
4502
4503 if (name == NULL) {
4504 // TODO:
4505 // ash emits: export VAR='VAL'
4506 // bash: declare -x VAR="VAL"
4507 // (both also escape as needed (quotes, $, etc))
4508 char **e = environ;
4509 if (e)
4510 while (*e)
4511 puts(*e++);
4512 return EXIT_SUCCESS;
4513 }
4514
4515 value = strchr(name, '=');
4516 if (!value) {
4517 /* They are exporting something without a =VALUE */
4518 struct variable *var;
4519
4520 var = get_local_var(name);
4521 if (var) {
4522 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004523 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004524 putenv(var->varstr);
4525 }
4526 /* bash does not return an error when trying to export
4527 * an undefined variable. Do likewise. */
4528 return EXIT_SUCCESS;
4529 }
4530
4531 set_local_var(xstrdup(name), 1);
4532 return EXIT_SUCCESS;
4533}
4534
4535#if ENABLE_HUSH_JOB
4536/* built-in 'fg' and 'bg' handler */
4537static int builtin_fg_bg(char **argv)
4538{
4539 int i, jobnum;
4540 struct pipe *pi;
4541
Denis Vlasenko87a86552008-07-29 19:43:10 +00004542 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004543 return EXIT_FAILURE;
4544 /* If they gave us no args, assume they want the last backgrounded task */
4545 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004546 for (pi = G.job_list; pi; pi = pi->next) {
4547 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004548 goto found;
4549 }
4550 }
4551 bb_error_msg("%s: no current job", argv[0]);
4552 return EXIT_FAILURE;
4553 }
4554 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4555 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4556 return EXIT_FAILURE;
4557 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004558 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004559 if (pi->jobid == jobnum) {
4560 goto found;
4561 }
4562 }
4563 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4564 return EXIT_FAILURE;
4565 found:
4566 // TODO: bash prints a string representation
4567 // of job being foregrounded (like "sleep 1 | cat")
4568 if (*argv[0] == 'f') {
4569 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004570 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004571 }
4572
4573 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004574 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4575 for (i = 0; i < pi->num_cmds; i++) {
4576 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4577 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004578 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004579 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004580
4581 i = kill(- pi->pgrp, SIGCONT);
4582 if (i < 0) {
4583 if (errno == ESRCH) {
4584 delete_finished_bg_job(pi);
4585 return EXIT_SUCCESS;
4586 } else {
4587 bb_perror_msg("kill (SIGCONT)");
4588 }
4589 }
4590
4591 if (*argv[0] == 'f') {
4592 remove_bg_job(pi);
4593 return checkjobs_and_fg_shell(pi);
4594 }
4595 return EXIT_SUCCESS;
4596}
4597#endif
4598
4599#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004600static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004601{
4602 const struct built_in_command *x;
4603
4604 printf("\nBuilt-in commands:\n");
4605 printf("-------------------\n");
4606 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4607 printf("%s\t%s\n", x->cmd, x->descr);
4608 }
4609 printf("\n\n");
4610 return EXIT_SUCCESS;
4611}
4612#endif
4613
4614#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004615static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004616{
4617 struct pipe *job;
4618 const char *status_string;
4619
Denis Vlasenko87a86552008-07-29 19:43:10 +00004620 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004621 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004622 status_string = "Stopped";
4623 else
4624 status_string = "Running";
4625
4626 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4627 }
4628 return EXIT_SUCCESS;
4629}
4630#endif
4631
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004632static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004633{
4634 puts(set_cwd());
4635 return EXIT_SUCCESS;
4636}
4637
4638static int builtin_read(char **argv)
4639{
4640 char *string;
4641 const char *name = argv[1] ? argv[1] : "REPLY";
4642
4643 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4644 return set_local_var(string, 0);
4645}
4646
4647/* built-in 'set [VAR=value]' handler */
4648static int builtin_set(char **argv)
4649{
4650 char *temp = argv[1];
4651 struct variable *e;
4652
4653 if (temp == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004654 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004655 puts(e->varstr);
4656 else
4657 set_local_var(xstrdup(temp), 0);
4658
4659 return EXIT_SUCCESS;
4660}
4661
4662static int builtin_shift(char **argv)
4663{
4664 int n = 1;
4665 if (argv[1]) {
4666 n = atoi(argv[1]);
4667 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004668 if (n >= 0 && n < G.global_argc) {
4669 G.global_argv[n] = G.global_argv[0];
4670 G.global_argc -= n;
4671 G.global_argv += n;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004672 return EXIT_SUCCESS;
4673 }
4674 return EXIT_FAILURE;
4675}
4676
4677static int builtin_source(char **argv)
4678{
4679 FILE *input;
4680 int status;
4681
4682 if (argv[1] == NULL)
4683 return EXIT_FAILURE;
4684
4685 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004686 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004687 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004688 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004689 return EXIT_FAILURE;
4690 }
4691 close_on_exec_on(fileno(input));
4692
4693 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004694 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004695 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00004696 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004697 status = parse_and_run_file(input);
4698 fclose(input);
4699 return status;
4700}
4701
4702static int builtin_umask(char **argv)
4703{
4704 mode_t new_umask;
4705 const char *arg = argv[1];
4706 char *end;
4707 if (arg) {
4708 new_umask = strtoul(arg, &end, 8);
4709 if (*end != '\0' || end == arg) {
4710 return EXIT_FAILURE;
4711 }
4712 } else {
4713 new_umask = umask(0);
4714 printf("%.3o\n", (unsigned) new_umask);
4715 }
4716 umask(new_umask);
4717 return EXIT_SUCCESS;
4718}
4719
4720static int builtin_unset(char **argv)
4721{
4722 /* bash always returns true */
4723 unset_local_var(argv[1]);
4724 return EXIT_SUCCESS;
4725}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004726
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004727#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004728static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004729{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004730 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004731 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004732 return EXIT_SUCCESS; /* bash compat */
4733 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004734 G.flag_break_continue++; /* BC_BREAK = 1 */
4735 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004736 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004737 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4738 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004739 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004740 G.flag_break_continue = BC_BREAK;
4741 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004742 }
4743 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004744 if (G.depth_of_loop < G.depth_break_continue)
4745 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004746 return EXIT_SUCCESS;
4747}
4748
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004749static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004750{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004751 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4752 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004753}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004754#endif