blob: 421272971a3a39fe5075ab6cae64a1ca2a864b84 [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 Vlasenkobe709c22008-07-28 00:01:16 +000070#include <glob.h>
71/* #include <dmalloc.h> */
72#if ENABLE_HUSH_CASE
73#include <fnmatch.h>
74#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +000075
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +000076#define HUSH_VER_STR "0.91"
Denis Vlasenkod01ff132007-05-02 21:40:23 +000077
Denis Vlasenko05743d72008-02-10 12:10:08 +000078#if !BB_MMU && ENABLE_HUSH_TICK
79//#undef ENABLE_HUSH_TICK
80//#define ENABLE_HUSH_TICK 0
81#warning On NOMMU, hush command substitution is dangerous.
82#warning Dont use it for commands which produce lots of output.
83#warning For more info see shell/hush.c, generate_stream_from_list().
84#endif
85
86#if !BB_MMU && ENABLE_HUSH_JOB
87#undef ENABLE_HUSH_JOB
88#define ENABLE_HUSH_JOB 0
89#endif
90
91#if !ENABLE_HUSH_INTERACTIVE
92#undef ENABLE_FEATURE_EDITING
93#define ENABLE_FEATURE_EDITING 0
94#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
95#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +000096#endif
97
98
Denis Vlasenko371de4a2008-10-14 12:43:13 +000099/* Keep unconditionally on for now */
100#define HUSH_DEBUG 1
101/* In progress... */
102#define ENABLE_HUSH_FUNCTIONS 0
103
104
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000105/* If you comment out one of these below, it will be #defined later
106 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000107#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000108/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000109#define debug_printf_parse(...) do {} while (0)
110#define debug_print_tree(a, b) do {} while (0)
111#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000112#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000113#define debug_printf_jobs(...) do {} while (0)
114#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000115#define debug_printf_glob(...) do {} while (0)
116#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000117#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000118#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000119
120#ifndef debug_printf
121#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000122#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000123
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000124#ifndef debug_printf_parse
125#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000126#endif
127
128#ifndef debug_printf_exec
129#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
130#endif
131
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000132#ifndef debug_printf_env
133#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
134#endif
135
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000136#ifndef debug_printf_jobs
137#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000138#define DEBUG_JOBS 1
139#else
140#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000141#endif
142
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000143#ifndef debug_printf_expand
144#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
145#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000146#else
147#define DEBUG_EXPAND 0
148#endif
149
150#ifndef debug_printf_glob
151#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
152#define DEBUG_GLOB 1
153#else
154#define DEBUG_GLOB 0
155#endif
156
157#ifndef debug_printf_list
158#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000159#endif
160
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000161#ifndef debug_printf_subst
162#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
163#endif
164
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000165#ifndef debug_printf_clean
166/* broken, of course, but OK for testing */
167static const char *indenter(int i)
168{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000169 static const char blanks[] ALIGN1 =
170 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000171 return &blanks[sizeof(blanks) - i - 1];
172}
173#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000174#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000175#endif
176
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000177#if DEBUG_EXPAND
178static void debug_print_strings(const char *prefix, char **vv)
179{
180 fprintf(stderr, "%s:\n", prefix);
181 while (*vv)
182 fprintf(stderr, " '%s'\n", *vv++);
183}
184#else
185#define debug_print_strings(prefix, vv) ((void)0)
186#endif
187
Denis Vlasenkof962a032007-11-23 12:50:54 +0000188/*
189 * Leak hunting. Use hush_leaktool.sh for post-processing.
190 */
191#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000192/* suppress "warning: no previous prototype..." */
193void *xxmalloc(int lineno, size_t size);
194void *xxrealloc(int lineno, void *ptr, size_t size);
195char *xxstrdup(int lineno, const char *str);
196void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000197void *xxmalloc(int lineno, size_t size)
198{
199 void *ptr = xmalloc((size + 0xff) & ~0xff);
200 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
201 return ptr;
202}
203void *xxrealloc(int lineno, void *ptr, size_t size)
204{
205 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
206 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
207 return ptr;
208}
209char *xxstrdup(int lineno, const char *str)
210{
211 char *ptr = xstrdup(str);
212 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
213 return ptr;
214}
215void xxfree(void *ptr)
216{
217 fprintf(stderr, "free %p\n", ptr);
218 free(ptr);
219}
220#define xmalloc(s) xxmalloc(__LINE__, s)
221#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
222#define xstrdup(s) xxstrdup(__LINE__, s)
223#define free(p) xxfree(p)
224#endif
225
226
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000227/* Do we support ANY keywords? */
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000228#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000229#define HAS_KEYWORDS 1
230#define IF_HAS_KEYWORDS(...) __VA_ARGS__
231#define IF_HAS_NO_KEYWORDS(...)
232#else
233#define HAS_KEYWORDS 0
234#define IF_HAS_KEYWORDS(...)
235#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
236#endif
237
238
Denis Vlasenko5703c222008-06-15 11:49:42 +0000239#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000240#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000241
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000242typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000243 REDIRECT_INPUT = 1,
244 REDIRECT_OVERWRITE = 2,
245 REDIRECT_APPEND = 3,
246 REDIRECT_HEREIS = 4,
247 REDIRECT_IO = 5
248} redir_type;
249
Denis Vlasenko55789c62008-06-18 16:30:42 +0000250/* The descrip member of this structure is only used to make
251 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000252static const struct {
253 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000254 signed char default_fd;
255 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000256} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000257 { 0, 0, "()" },
258 { O_RDONLY, 0, "<" },
259 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
260 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
261 { O_RDONLY, -1, "<<" },
262 { O_RDWR, 1, "<>" }
263};
264
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000265typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000266 PIPE_SEQ = 1,
267 PIPE_AND = 2,
268 PIPE_OR = 3,
269 PIPE_BG = 4,
270} pipe_style;
271
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000272typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000273 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000274#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000275 RES_IF ,
276 RES_THEN ,
277 RES_ELIF ,
278 RES_ELSE ,
279 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000280#endif
281#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000282 RES_FOR ,
283 RES_WHILE ,
284 RES_UNTIL ,
285 RES_DO ,
286 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000287#endif
288#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000289 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000290#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000291#if ENABLE_HUSH_CASE
292 RES_CASE ,
293 /* two pseudo-keywords support contrived "case" syntax: */
294 RES_MATCH , /* "word)" */
295 RES_CASEI , /* "this command is inside CASE" */
296 RES_ESAC ,
297#endif
298 RES_XXXX ,
299 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000300} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000301
Eric Andersen25f27032001-04-26 23:22:31 +0000302struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000303 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000304 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000305 int fd; /* file descriptor being redirected */
306 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000307 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000308};
309
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000310struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000311 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000312 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000313 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000314 smallint grp_type;
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000315 struct pipe *group; /* if non-NULL, this "prog" is {} group,
316 * subshell, or a compound statement */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000317 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000318 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000319};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000320/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
321 * and on execution these are substituted with their values.
322 * Substitution can make _several_ words out of one argv[n]!
323 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000324 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000325 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000326#define GRP_NORMAL 0
327#define GRP_SUBSHELL 1
328#if ENABLE_HUSH_FUNCTIONS
329#define GRP_FUNCTION 2
330#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000331
332struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000333 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000334 int num_cmds; /* total number of commands in job */
335 int alive_cmds; /* number of commands running (not exited) */
336 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000337#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000338 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000339 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000340 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000341#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000342 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000343 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000344 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
345 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000346};
347
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000348/* This holds pointers to the various results of parsing */
349struct parse_context {
350 struct command *command;
351 struct pipe *list_head;
352 struct pipe *pipe;
353 struct redir_struct *pending_redirect;
354#if HAS_KEYWORDS
355 smallint ctx_res_w;
356 smallint ctx_inverted; /* "! cmd | cmd" */
357#if ENABLE_HUSH_CASE
358 smallint ctx_dsemicolon; /* ";;" seen */
359#endif
360 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
361 struct parse_context *stack;
362#endif
363};
364
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000365/* On program start, environ points to initial environment.
366 * putenv adds new pointers into it, unsetenv removes them.
367 * Neither of these (de)allocates the strings.
368 * setenv allocates new strings in malloc space and does putenv,
369 * and thus setenv is unusable (leaky) for shell's purposes */
370#define setenv(...) setenv_is_leaky_dont_use()
371struct variable {
372 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000373 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000374 int max_len; /* if > 0, name is part of initial env; else name is malloced */
375 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000376 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000377};
378
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000379typedef struct o_string {
Eric Andersen25f27032001-04-26 23:22:31 +0000380 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000381 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000382 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000383 /* Misnomer! it's not "quoting", it's "protection against globbing"!
384 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000385 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000386 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000387 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000388 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000389 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000390} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000391enum {
392 MAYBE_ASSIGNMENT = 0,
393 DEFINITELY_ASSIGNMENT = 1,
394 NOT_ASSIGNMENT = 2,
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000395 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000396};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000397/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000398#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000399
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000400/* I can almost use ordinary FILE*. Is open_memstream() universally
Eric Andersen25f27032001-04-26 23:22:31 +0000401 * available? Where is it documented? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000402typedef struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000403 const char *p;
404 /* eof_flag=1: last char in ->p is really an EOF */
405 char eof_flag; /* meaningless if ->p == NULL */
406 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000407#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000408 smallint promptme;
409 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000410#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000411 FILE *file;
412 int (*get) (struct in_str *);
413 int (*peek) (struct in_str *);
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000414} in_str;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000415#define i_getch(input) ((input)->get(input))
416#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000417
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000418enum {
419 CHAR_ORDINARY = 0,
420 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
421 CHAR_IFS = 2, /* treated as ordinary if quoted */
422 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000423};
424
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000425enum {
426 BC_BREAK = 1,
427 BC_CONTINUE = 2,
428};
429
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000430
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000431/* "Globals" within this file */
432
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000433/* Sorted roughly by size (smaller offsets == smaller code) */
434struct globals {
435#if ENABLE_HUSH_INTERACTIVE
436 /* 'interactive_fd' is a fd# open to ctty, if we have one
437 * _AND_ if we decided to act interactively */
438 int interactive_fd;
439 const char *PS1;
440 const char *PS2;
441#endif
442#if ENABLE_FEATURE_EDITING
443 line_input_t *line_input_state;
444#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000445 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000446 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000447#if ENABLE_HUSH_JOB
448 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000449 pid_t saved_tty_pgrp;
450 int last_jobid;
451 struct pipe *job_list;
452 struct pipe *toplevel_list;
453 smallint ctrl_z_flag;
454#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000455#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000456 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000457#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000458 smallint fake_mode;
459 /* these three support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000460 smalluint last_return_code;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000461 char **global_argv;
462 int global_argc;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000463#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000464 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000465 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000466#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000467 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000468 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000469 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000470 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000471#if ENABLE_FEATURE_SH_STANDALONE
472 struct nofork_save_area nofork_save;
473#endif
474#if ENABLE_HUSH_JOB
475 sigjmp_buf toplevel_jb;
476#endif
477 unsigned char charmap[256];
478 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
479};
480
481#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000482/* Not #defining name to G.name - this quickly gets unwieldy
483 * (too many defines). Also, I actually prefer to see when a variable
484 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000485#define INIT_G() do { \
486 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
487} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000488
489
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000490#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
491
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000492#if 1
493/* Normal */
494static void syntax(const char *msg)
495{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000496#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000497 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000498 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000499 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000500 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000501 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000502 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000503#else
504 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
505#endif
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000506}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000507
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000508#else
509/* Debug */
510static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000511{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000512#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoff182a32008-07-05 20:29:59 +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("syntax error hush.c:%d", line);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000516#else
517 bb_error_msg_and_die("syntax error hush.c:%d", line);
518#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000519}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000520#define syntax(str) syntax_lineno(__LINE__)
521#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000522
523/* Index of subroutines: */
Eric Andersen25f27032001-04-26 23:22:31 +0000524/* in_str manipulations: */
525static int static_get(struct in_str *i);
526static int static_peek(struct in_str *i);
527static int file_get(struct in_str *i);
528static int file_peek(struct in_str *i);
529static void setup_file_in_str(struct in_str *i, FILE *f);
530static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000531/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000532#if !defined(DEBUG_CLEAN)
533#define free_pipe_list(head, indent) free_pipe_list(head)
534#define free_pipe(pi, indent) free_pipe(pi)
535#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000536static int free_pipe_list(struct pipe *head, int indent);
537static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000538/* really run the final data structures: */
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000539typedef struct nommu_save_t {
540 char **new_env;
541 char **old_env;
542 char **argv;
543} nommu_save_t;
Denis Vlasenko76d50412008-06-10 16:19:39 +0000544#if BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000545#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000546 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000547#define pseudo_exec(nommu_save, command, argv_expanded) \
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000548 pseudo_exec(command, argv_expanded)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000549#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000550static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
551static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
552static int setup_redirects(struct command *prog, int squirrel[]);
553static int run_list(struct pipe *pi);
Denis Vlasenko05743d72008-02-10 12:10:08 +0000554static int run_pipe(struct pipe *pi);
Eric Andersen25f27032001-04-26 23:22:31 +0000555/* data structure manipulation: */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000556static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
557static void initialize_context(struct parse_context *ctx);
558static int done_word(o_string *dest, struct parse_context *ctx);
559static int done_command(struct parse_context *ctx);
560static void done_pipe(struct parse_context *ctx, pipe_style type);
Eric Andersen25f27032001-04-26 23:22:31 +0000561/* primary string parsing: */
562static int redirect_dup_num(struct in_str *input);
563static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000564#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000565static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000566 struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000567#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000568static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000569static const char *lookup_param(const char *src);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000570static int handle_dollar(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000571 struct in_str *input);
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000572static 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 +0000573/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000574static int parse_and_run_stream(struct in_str *inp, int parse_flag);
575static int parse_and_run_string(const char *s, int parse_flag);
576static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000577/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000578static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000579#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000580static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000581static void insert_bg_job(struct pipe *pi);
582static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000583static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000584#else
585int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
586#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000587/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000588static char **expand_strvec_to_strvec(char **argv);
589/* used for eval */
590static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000591/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000592static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000593static struct variable *get_local_var(const char *name);
594static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000595static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000596
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000597
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000598static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
599
600
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000601static int glob_needed(const char *s)
602{
603 while (*s) {
604 if (*s == '\\')
605 s++;
606 if (*s == '*' || *s == '[' || *s == '?')
607 return 1;
608 s++;
609 }
610 return 0;
611}
612
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000613static int is_assignment(const char *s)
614{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000615 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000616 return 0;
617 s++;
618 while (isalnum(*s) || *s == '_')
619 s++;
620 return *s == '=';
621}
622
Denis Vlasenko55789c62008-06-18 16:30:42 +0000623/* Replace each \x with x in place, return ptr past NUL. */
624static char *unbackslash(char *src)
625{
626 char *dst = src;
627 while (1) {
628 if (*src == '\\')
629 src++;
630 if ((*dst++ = *src++) == '\0')
631 break;
632 }
633 return dst;
634}
635
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000636static char **add_strings_to_strings(char **strings, char **add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000637{
638 int i;
639 unsigned count1;
640 unsigned count2;
641 char **v;
642
643 v = strings;
644 count1 = 0;
645 if (v) {
646 while (*v) {
647 count1++;
648 v++;
649 }
650 }
651 count2 = 0;
652 v = add;
653 while (*v) {
654 count2++;
655 v++;
656 }
657 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
658 v[count1 + count2] = NULL;
659 i = count2;
660 while (--i >= 0)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000661 v[count1 + i] = add[i];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000662 return v;
663}
664
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000665static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000666{
667 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000668 v[0] = add;
669 v[1] = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000670 return add_strings_to_strings(strings, v);
671}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000672
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000673static void putenv_all(char **strings)
674{
675 if (!strings)
676 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000677 while (*strings) {
678 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000679 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000680 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000681}
682
683static char **putenv_all_and_save_old(char **strings)
684{
685 char **old = NULL;
686 char **s = strings;
687
688 if (!strings)
689 return old;
690 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000691 char *v, *eq;
692
693 eq = strchr(*strings, '=');
694 if (eq) {
695 *eq = '\0';
696 v = getenv(*strings);
697 *eq = '=';
698 if (v) {
699 /* v points to VAL in VAR=VAL, go back to VAR */
700 v -= (eq - *strings) + 1;
701 old = add_string_to_strings(old, v);
702 }
703 }
704 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000705 }
706 putenv_all(s);
707 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000708}
709
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000710static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000711{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000712 char **v;
713
714 if (!strings)
715 return;
716
717 v = strings;
718 while (*v) {
719 if (unset) {
720 char *copy;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000721 /* *strchrnul(*v, '=') = '\0'; -- BAD
722 * In case *v was putenv'ed, we can't
723 * unsetenv(*v) after taking out '=':
724 * it won't work, env is modified by taking out!
725 * horror :( */
726 copy = xstrndup(*v, strchrnul(*v, '=') - *v);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000727 debug_printf_env("unsetenv '%s'\n", copy);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000728 unsetenv(copy);
729 free(copy);
730 }
731 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000732 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000733 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000734}
735
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000736static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000737{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000738 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000739}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000740
741
Denis Vlasenko83506862007-11-23 13:11:42 +0000742/* Function prototypes for builtins */
743static int builtin_cd(char **argv);
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000744static int builtin_echo(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000745static int builtin_eval(char **argv);
746static int builtin_exec(char **argv);
747static int builtin_exit(char **argv);
748static int builtin_export(char **argv);
749#if ENABLE_HUSH_JOB
750static int builtin_fg_bg(char **argv);
751static int builtin_jobs(char **argv);
752#endif
753#if ENABLE_HUSH_HELP
754static int builtin_help(char **argv);
755#endif
756static int builtin_pwd(char **argv);
757static int builtin_read(char **argv);
758static int builtin_test(char **argv);
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000759static int builtin_true(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000760static int builtin_set(char **argv);
761static int builtin_shift(char **argv);
762static int builtin_source(char **argv);
763static int builtin_umask(char **argv);
764static int builtin_unset(char **argv);
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000765#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000766static int builtin_break(char **argv);
767static int builtin_continue(char **argv);
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000768#endif
Denis Vlasenko83506862007-11-23 13:11:42 +0000769//static int builtin_not_written(char **argv);
770
Eric Andersen25f27032001-04-26 23:22:31 +0000771/* Table of built-in functions. They can be forked or not, depending on
772 * context: within pipes, they fork. As simple commands, they do not.
773 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000774 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000775 * For example, 'unset foo | whatever' will parse and run, but foo will
776 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000777struct built_in_command {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000778 const char *cmd;
779 int (*function)(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000780#if ENABLE_HUSH_HELP
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000781 const char *descr;
Denis Vlasenko06810332007-05-21 23:30:54 +0000782#define BLTIN(cmd, func, help) { cmd, func, help }
783#else
784#define BLTIN(cmd, func, help) { cmd, func }
785#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000786};
787
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000788/* For now, echo and test are unconditionally enabled.
789 * Maybe make it configurable? */
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000790static const struct built_in_command bltins[] = {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000791 BLTIN("." , builtin_source, "Run commands in a file"),
792 BLTIN(":" , builtin_true, "No-op"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000793 BLTIN("[" , builtin_test, "Test condition"),
794 BLTIN("[[" , builtin_test, "Test condition"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000795#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000796 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000797#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000798#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000799 BLTIN("break" , builtin_break, "Exit from a loop"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000800#endif
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000801 BLTIN("cd" , builtin_cd, "Change directory"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000802#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000803 BLTIN("continue", builtin_continue, "Start new loop iteration"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000804#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000805 BLTIN("echo" , builtin_echo, "Write to stdout"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000806 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000807 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
808 BLTIN("exit" , builtin_exit, "Exit"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000809 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000810#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000811 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000812 BLTIN("jobs" , builtin_jobs, "List active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000813#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000814 BLTIN("pwd" , builtin_pwd, "Print current directory"),
815 BLTIN("read" , builtin_read, "Input environment variable"),
816// BLTIN("return", builtin_not_written, "Return from a function"),
817 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
818 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
819// BLTIN("trap" , builtin_not_written, "Trap signals"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000820 BLTIN("test" , builtin_test, "Test condition"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000821// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
822 BLTIN("umask" , builtin_umask, "Set file creation mask"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000823 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000824#if ENABLE_HUSH_HELP
825 BLTIN("help" , builtin_help, "List shell built-in commands"),
826#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000827};
828
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000829
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000830/* Signals are grouped, we handle them in batches */
831static void set_misc_sighandler(void (*handler)(int))
832{
833 bb_signals(0
834 + (1 << SIGINT)
835 + (1 << SIGQUIT)
836 + (1 << SIGTERM)
837 , handler);
838}
839
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000840#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000841
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000842static void set_fatal_sighandler(void (*handler)(int))
843{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000844 bb_signals(0
845 + (1 << SIGILL)
846 + (1 << SIGTRAP)
847 + (1 << SIGABRT)
848 + (1 << SIGFPE)
849 + (1 << SIGBUS)
850 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000851 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000852 + (1 << SIGHUP)
853 + (1 << SIGPIPE)
854 + (1 << SIGALRM)
855 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000856}
857static void set_jobctrl_sighandler(void (*handler)(int))
858{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000859 bb_signals(0
860 + (1 << SIGTSTP)
861 + (1 << SIGTTIN)
862 + (1 << SIGTTOU)
863 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000864}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000865/* SIGCHLD is special and handled separately */
866
867static void set_every_sighandler(void (*handler)(int))
868{
869 set_fatal_sighandler(handler);
870 set_jobctrl_sighandler(handler);
871 set_misc_sighandler(handler);
872 signal(SIGCHLD, handler);
873}
874
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000875static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000876{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000877 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000878// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000879 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000880}
881
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000882static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000883{
884 pid_t pid;
885
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000886 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000887 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000888 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000889 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000890 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000891 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000892 if (ENABLE_HUSH_JOB)
893 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000894 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000895 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000896 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000897 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000898 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000899 /* return to nofork, it will eventually exit now,
900 * not return back to shell */
901 return;
902 }
903 /* parent */
904 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000905 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000906 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000907 /* parent needs to longjmp out of running nofork.
908 * we will "return" exitcode 0, with child put in background */
909// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000910 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000911 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000912}
913
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000914/* Restores tty foreground process group, and exits.
915 * May be called as signal handler for fatal signal
916 * (will faithfully resend signal to itself, producing correct exit state)
917 * or called directly with -EXITCODE.
918 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000919static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000920static void sigexit(int sig)
921{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000922 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000923 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000924
Denis Vlasenko87a86552008-07-29 19:43:10 +0000925#if ENABLE_HUSH_INTERACTIVE
926 if (G.interactive_fd)
927 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
928#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000929
930 /* Not a signal, just exit */
931 if (sig <= 0)
932 _exit(- sig);
933
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000934 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000935}
936
937/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000938static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000939static void hush_exit(int exitcode)
940{
941 fflush(NULL); /* flush all streams */
942 sigexit(- (exitcode & 0xff));
943}
944
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000945#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000946
947#define set_fatal_sighandler(handler) ((void)0)
948#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000949#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000950
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000951#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000952
953
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000954static const char *set_cwd(void)
955{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000956 if (G.cwd == bb_msg_unknown)
957 G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
958 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
959 if (!G.cwd)
960 G.cwd = bb_msg_unknown;
961 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000962}
963
Denis Vlasenko83506862007-11-23 13:11:42 +0000964
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000965/*
966 * o_string support
967 */
968#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +0000969
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000970static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000971{
972 o->length = 0;
973 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000974 if (o->data)
975 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000976}
977
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000978static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000979{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +0000980 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000981 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +0000982}
983
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000984static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000985{
986 if (o->length + len > o->maxlen) {
987 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
988 o->data = xrealloc(o->data, 1 + o->maxlen);
989 }
990}
991
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000992static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000993{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000994 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
995 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000996 o->data[o->length] = ch;
997 o->length++;
998 o->data[o->length] = '\0';
999}
1000
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001001static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001002{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001003 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001004 memcpy(&o->data[o->length], str, len);
1005 o->length += len;
1006 o->data[o->length] = '\0';
1007}
1008
Denis Vlasenko55789c62008-06-18 16:30:42 +00001009static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1010{
1011 while (len) {
1012 o_addchr(o, *str);
1013 if (*str++ == '\\'
1014 && (*str != '*' && *str != '?' && *str != '[')
1015 ) {
1016 o_addchr(o, '\\');
1017 }
1018 len--;
1019 }
1020}
1021
Eric Andersen25f27032001-04-26 23:22:31 +00001022/* My analysis of quoting semantics tells me that state information
1023 * is associated with a destination, not a source.
1024 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001025static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001026{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001027 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001028 char *found = strchr("*?[\\", ch);
1029 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001030 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001031 o_grow_by(o, sz);
1032 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001033 o->data[o->length] = '\\';
1034 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001035 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001036 o->data[o->length] = ch;
1037 o->length++;
1038 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001039}
1040
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001041static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001042{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001043 int sz = 1;
1044 if (o->o_quote && strchr("*?[\\", ch)) {
1045 sz++;
1046 o->data[o->length] = '\\';
1047 o->length++;
1048 }
1049 o_grow_by(o, sz);
1050 o->data[o->length] = ch;
1051 o->length++;
1052 o->data[o->length] = '\0';
1053}
1054
1055static void o_addQstr(o_string *o, const char *str, int len)
1056{
1057 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001058 o_addstr(o, str, len);
1059 return;
1060 }
1061 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001062 char ch;
1063 int sz;
1064 int ordinary_cnt = strcspn(str, "*?[\\");
1065 if (ordinary_cnt > len) /* paranoia */
1066 ordinary_cnt = len;
1067 o_addstr(o, str, ordinary_cnt);
1068 if (ordinary_cnt == len)
1069 return;
1070 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001071 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001072
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001073 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001074 sz = 1;
1075 if (ch) { /* it is necessarily one of "*?[\\" */
1076 sz++;
1077 o->data[o->length] = '\\';
1078 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001079 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001080 o_grow_by(o, sz);
1081 o->data[o->length] = ch;
1082 o->length++;
1083 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001084 }
1085}
1086
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001087/* A special kind of o_string for $VAR and `cmd` expansion.
1088 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001089 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001090 * list[i] contains an INDEX (int!) into this string data.
1091 * It means that if list[] needs to grow, data needs to be moved higher up
1092 * but list[i]'s need not be modified.
1093 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001094 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001095 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1096 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001097#if DEBUG_EXPAND || DEBUG_GLOB
1098static void debug_print_list(const char *prefix, o_string *o, int n)
1099{
1100 char **list = (char**)o->data;
1101 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1102 int i = 0;
1103 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1104 prefix, list, n, string_start, o->length, o->maxlen);
1105 while (i < n) {
1106 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1107 o->data + (int)list[i] + string_start,
1108 o->data + (int)list[i] + string_start);
1109 i++;
1110 }
1111 if (n) {
1112 const char *p = o->data + (int)list[n - 1] + string_start;
1113 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1114 }
1115}
1116#else
1117#define debug_print_list(prefix, o, n) ((void)0)
1118#endif
1119
1120/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1121 * in list[n] so that it points past last stored byte so far.
1122 * It returns n+1. */
1123static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001124{
1125 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001126 int string_start;
1127 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001128
1129 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001130 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1131 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001132 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001133 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001134 /* list[n] points to string_start, make space for 16 more pointers */
1135 o->maxlen += 0x10 * sizeof(list[0]);
1136 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001137 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001138 memmove(list + n + 0x10, list + n, string_len);
1139 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001140 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001141 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001142 } else {
1143 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001144 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1145 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001146 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001147 o->has_empty_slot = 0;
1148 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001149 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001150 return n + 1;
1151}
1152
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001153/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001154static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001155{
1156 char **list = (char**)o->data;
1157 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1158
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001159 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001160}
1161
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001162/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001163 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001164static int o_glob(o_string *o, int n)
1165{
1166 glob_t globdata;
1167 int gr;
1168 char *pattern;
1169
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001170 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001171 if (!o->data)
1172 return o_save_ptr_helper(o, n);
1173 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001174 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001175 if (!glob_needed(pattern)) {
1176 literal:
1177 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001178 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001179 return o_save_ptr_helper(o, n);
1180 }
1181
1182 memset(&globdata, 0, sizeof(globdata));
1183 gr = glob(pattern, 0, NULL, &globdata);
1184 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1185 if (gr == GLOB_NOSPACE)
1186 bb_error_msg_and_die("out of memory during glob");
1187 if (gr == GLOB_NOMATCH) {
1188 globfree(&globdata);
1189 goto literal;
1190 }
1191 if (gr != 0) { /* GLOB_ABORTED ? */
1192//TODO: testcase for bad glob pattern behavior
1193 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1194 }
1195 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1196 char **argv = globdata.gl_pathv;
1197 o->length = pattern - o->data; /* "forget" pattern */
1198 while (1) {
1199 o_addstr(o, *argv, strlen(*argv) + 1);
1200 n = o_save_ptr_helper(o, n);
1201 argv++;
1202 if (!*argv)
1203 break;
1204 }
1205 }
1206 globfree(&globdata);
1207 if (DEBUG_GLOB)
1208 debug_print_list("o_glob returning", o, n);
1209 return n;
1210}
1211
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001212/* If o->o_glob == 1, glob the string so far remembered.
1213 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001214static int o_save_ptr(o_string *o, int n)
1215{
1216 if (o->o_glob)
1217 return o_glob(o, n); /* o_save_ptr_helper is inside */
1218 return o_save_ptr_helper(o, n);
1219}
1220
1221/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001222static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001223{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001224 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001225 int string_start;
1226
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001227 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1228 if (DEBUG_EXPAND)
1229 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001230 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001231 list = (char**)o->data;
1232 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1233 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001234 while (n) {
1235 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001236 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001237 }
1238 return list;
1239}
1240
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001241
1242/*
1243 * in_str support
1244 */
Eric Andersen25f27032001-04-26 23:22:31 +00001245static int static_get(struct in_str *i)
1246{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001247 int ch = *i->p++;
1248 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001249 return ch;
1250}
1251
1252static int static_peek(struct in_str *i)
1253{
1254 return *i->p;
1255}
1256
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001257#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001258
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001259#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001260static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001261{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001262#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denis Vlasenko87a86552008-07-29 19:43:10 +00001263 G.PS1 = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00001264#else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001265 G.PS1 = getenv("PS1");
1266 if (G.PS1 == NULL)
1267 G.PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001268#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001269}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001270#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001271
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001272static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001273{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001274 const char *prompt_str;
1275 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001276#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001277 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001278 if (promptmode == 0) { /* PS1 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001279 free((char*)G.PS1);
1280 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1281 prompt_str = G.PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001282 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001283 prompt_str = G.PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001284 }
1285#else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001286 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001287#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001288 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001289 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001290}
1291
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001292static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001293{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001294 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001295 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001296
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001297 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001298#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001299 /* Enable command line editing only while a command line
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001300 * is actually being read */
1301 do {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001302 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001303 } while (r == 0); /* repeat if Ctrl-C */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001304 i->eof_flag = (r < 0);
1305 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001306 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1307 G.user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001308 }
Eric Andersen25f27032001-04-26 23:22:31 +00001309#else
1310 fputs(prompt_str, stdout);
1311 fflush(stdout);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001312 G.user_input_buf[0] = r = fgetc(i->file);
1313 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001314 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001315#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00001316 i->p = G.user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001317}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001318
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001319#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001320
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001321/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001322 * and gets data back from the user */
1323static int file_get(struct in_str *i)
1324{
1325 int ch;
1326
Eric Andersen25f27032001-04-26 23:22:31 +00001327 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001328 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001329#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001330 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001331#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001332 ch = *i->p++;
1333 if (i->eof_flag && !*i->p)
1334 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001335 } else {
1336 /* need to double check i->file because we might be doing something
1337 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001338#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +00001339 if (G.interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001340 do {
1341 get_user_input(i);
1342 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001343 i->promptmode = 1; /* PS2 */
1344 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001345 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001346 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001347#endif
1348 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001349 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001350 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001351#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001352 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001353 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001354#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001355 return ch;
1356}
1357
1358/* All the callers guarantee this routine will never be
1359 * used right after a newline, so prompting is not needed.
1360 */
1361static int file_peek(struct in_str *i)
1362{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001363 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001364 if (i->p && *i->p) {
1365 if (i->eof_flag && !i->p[1])
1366 return EOF;
1367 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001368 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001369 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001370 i->eof_flag = (ch == EOF);
1371 i->peek_buf[0] = ch;
1372 i->peek_buf[1] = '\0';
1373 i->p = i->peek_buf;
1374 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001375 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001376}
1377
1378static void setup_file_in_str(struct in_str *i, FILE *f)
1379{
1380 i->peek = file_peek;
1381 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001382#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001383 i->promptme = 1;
1384 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001385#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001386 i->file = f;
1387 i->p = NULL;
1388}
1389
1390static void setup_string_in_str(struct in_str *i, const char *s)
1391{
1392 i->peek = static_peek;
1393 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001394#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001395 i->promptme = 1;
1396 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001397#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001398 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001399 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001400}
1401
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001402
Eric Andersen25f27032001-04-26 23:22:31 +00001403/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1404 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001405static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001406{
1407 int openfd, mode;
1408 struct redir_struct *redir;
1409
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001410 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001411 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001412 /* something went wrong in the parse. Pretend it didn't happen */
1413 continue;
1414 }
Eric Andersen25f27032001-04-26 23:22:31 +00001415 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001416 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001417 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001418//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001419 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001420 openfd = open_or_warn(p, mode);
1421 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001422 if (openfd < 0) {
1423 /* this could get lost if stderr has been redirected, but
1424 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001425 return 1;
1426 }
1427 } else {
1428 openfd = redir->dup;
1429 }
1430
1431 if (openfd != redir->fd) {
1432 if (squirrel && redir->fd < 3) {
1433 squirrel[redir->fd] = dup(redir->fd);
1434 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001435 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001436 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001437 } else {
1438 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001439 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001440 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001441 }
Eric Andersen25f27032001-04-26 23:22:31 +00001442 }
1443 }
1444 return 0;
1445}
1446
1447static void restore_redirects(int squirrel[])
1448{
1449 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001450 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001451 fd = squirrel[i];
1452 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001453 /* We simply die on error */
1454 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001455 }
1456 }
1457}
1458
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001459static char **expand_assignments(char **argv, int count)
1460{
1461 int i;
1462 char **p = NULL;
1463 /* Expand assignments into one string each */
1464 for (i = 0; i < count; i++) {
1465 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1466 }
1467 return p;
1468}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001469
Denis Vlasenko05743d72008-02-10 12:10:08 +00001470/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001471 * Never returns.
1472 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001473 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001474 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001475static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001476{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001477 int rcode;
1478 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001479 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001480
Denis Vlasenko1359da62007-04-21 23:27:30 +00001481 /* If a variable is assigned in a forest, and nobody listens,
1482 * was it ever really set?
1483 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001484 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001485 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001486
Denis Vlasenko9504e442008-10-29 01:19:15 +00001487 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001488#if BB_MMU
1489 putenv_all(new_env);
1490 free(new_env); /* optional */
1491#else
1492 nommu_save->new_env = new_env;
1493 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001494#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001495 if (argv_expanded) {
1496 argv = argv_expanded;
1497 } else {
1498 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001499#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001500 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00001501#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001502 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001503
Denis Vlasenko1359da62007-04-21 23:27:30 +00001504 /*
1505 * Check if the command matches any of the builtins.
1506 * Depending on context, this might be redundant. But it's
1507 * easier to waste a few CPU cycles than it is to figure out
1508 * if this is one of those cases.
1509 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001510 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001511 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001512 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001513 rcode = x->function(argv);
1514 fflush(stdout);
1515 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001516 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001517 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001518
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001519 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001520#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001521 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001522 int a = find_applet_by_name(argv[0]);
1523 if (a >= 0) {
1524 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001525 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001526// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1527 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001528 }
1529 /* re-exec ourselves with the new arguments */
1530 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001531 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001532 /* If they called chroot or otherwise made the binary no longer
1533 * executable, fall through */
1534 }
1535 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001536#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001537
1538 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001539 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00001540 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001541 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001542}
1543
Denis Vlasenko05743d72008-02-10 12:10:08 +00001544/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001545 */
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001546static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001547{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001548 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001549 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001550
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001551 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001552#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001553 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001554#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001555 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001556 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001557 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001558 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001559 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001560 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001561#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001562 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001563
1564 /* Can happen. See what bash does with ">foo" by itself. */
1565 debug_printf("trying to pseudo_exec null command\n");
1566 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001567}
1568
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001569#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001570static const char *get_cmdtext(struct pipe *pi)
1571{
1572 char **argv;
1573 char *p;
1574 int len;
1575
1576 /* This is subtle. ->cmdtext is created only on first backgrounding.
1577 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001578 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001579 if (pi->cmdtext)
1580 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001581 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001582 if (!argv || !argv[0]) {
1583 pi->cmdtext = xzalloc(1);
1584 return pi->cmdtext;
1585 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001586
1587 len = 0;
1588 do len += strlen(*argv) + 1; while (*++argv);
1589 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001590 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001591 do {
1592 len = strlen(*argv);
1593 memcpy(p, *argv, len);
1594 p += len;
1595 *p++ = ' ';
1596 } while (*++argv);
1597 p[-1] = '\0';
1598 return pi->cmdtext;
1599}
1600
Eric Andersenbafd94f2001-05-02 16:11:59 +00001601static void insert_bg_job(struct pipe *pi)
1602{
1603 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001604 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001605
1606 /* Linear search for the ID of the job to use */
1607 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001608 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001609 if (thejob->jobid >= pi->jobid)
1610 pi->jobid = thejob->jobid + 1;
1611
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001612 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001613 if (!G.job_list) {
1614 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001615 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001616 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001617 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001618 thejob->next = xmalloc(sizeof(*thejob));
1619 thejob = thejob->next;
1620 }
1621
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001622 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001623 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001624 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
1625 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
1626 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001627// TODO: do we really need to have so many fields which are just dead weight
1628// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001629 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001630 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001631 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001632 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001633 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001634
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001635 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001636 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001637 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
1638 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001639 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001640}
1641
Eric Andersenbafd94f2001-05-02 16:11:59 +00001642static void remove_bg_job(struct pipe *pi)
1643{
1644 struct pipe *prev_pipe;
1645
Denis Vlasenko87a86552008-07-29 19:43:10 +00001646 if (pi == G.job_list) {
1647 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001648 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001649 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001650 while (prev_pipe->next != pi)
1651 prev_pipe = prev_pipe->next;
1652 prev_pipe->next = pi->next;
1653 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001654 if (G.job_list)
1655 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00001656 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001657 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001658}
Eric Andersen028b65b2001-06-28 01:10:11 +00001659
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001660/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001661static void delete_finished_bg_job(struct pipe *pi)
1662{
1663 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001664 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001665 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001666 free(pi);
1667}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001668#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001669
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001670/* Check to see if any processes have exited -- if they
1671 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001672static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001673{
Eric Andersenc798b072001-06-22 06:23:03 +00001674 int attributes;
1675 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001676#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001677 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001678#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001679 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001680 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001681
Eric Andersenc798b072001-06-22 06:23:03 +00001682 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001683 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00001684 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00001685
Denis Vlasenko1359da62007-04-21 23:27:30 +00001686/* Do we do this right?
1687 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001688 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001689 * [3]+ Stopped sleep 20 | false
1690 * bash-3.00# echo $?
1691 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1692 */
1693
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001694//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1695//are stopped. Testcase: "cat | cat" in a script (not on command line)
1696// + killall -STOP cat
1697
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001698 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00001699// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00001700 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001701 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001702 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001703#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00001704 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001705 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001706 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1707 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001708 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001709 childpid, WTERMSIG(status), WEXITSTATUS(status));
1710 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001711 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001712 childpid, WEXITSTATUS(status));
1713#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001714 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001715 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001716 for (i = 0; i < fg_pipe->num_cmds; i++) {
1717 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
1718 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001719 continue;
1720 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1721 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001722 fg_pipe->cmds[i].pid = 0;
1723 fg_pipe->alive_cmds--;
1724 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001725 /* last process gives overall exitstatus */
1726 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001727 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001728 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001729 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001730 fg_pipe->cmds[i].is_stopped = 1;
1731 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00001732 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001733 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
1734 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
1735 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001736 /* All processes in fg pipe have exited/stopped */
1737#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001738 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001739 insert_bg_job(fg_pipe);
1740#endif
1741 return rcode;
1742 }
1743 /* There are still running processes in the fg pipe */
1744 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00001745 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001746 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001747 }
1748
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001749#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001750 /* We asked to wait for bg or orphaned children */
1751 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001752 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001753 for (i = 0; i < pi->num_cmds; i++) {
1754 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001755 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001756 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001757 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001758 /* Happens when shell is used as init process (init=/bin/sh) */
1759 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001760 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00001761
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001762 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001763 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001764 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001765 pi->cmds[i].pid = 0;
1766 pi->alive_cmds--;
1767 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001768 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001769 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001770 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001771 }
1772 } else {
1773 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001774 pi->cmds[i].is_stopped = 1;
1775 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001776 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001777#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001778 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001779
Denis Vlasenko1359da62007-04-21 23:27:30 +00001780 /* wait found no children or failed */
1781
1782 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001783 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001784 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001785}
1786
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001787#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001788static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1789{
1790 pid_t p;
1791 int rcode = checkjobs(fg_pipe);
1792 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001793 p = getpgid(0); /* pgid of our process */
1794 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001795 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001796 return rcode;
1797}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001798#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001799
Denis Vlasenko05743d72008-02-10 12:10:08 +00001800/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001801 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001802 *
1803 * return code is normally -1, when the caller has to wait for children
1804 * to finish to determine the exit status of the pipe. If the pipe
1805 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00001806 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00001807 * return value.
1808 *
1809 * The input of the pipe is always stdin, the output is always
1810 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1811 * because it tries to avoid running the command substitution in
1812 * subshell, when that is in fact necessary. The subshell process
1813 * now has its stdout directed to the input of the appropriate pipe,
1814 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001815 *
1816 * Returns -1 only if started some children. IOW: we have to
1817 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001818 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001819static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001820{
1821 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001822 int nextin;
1823 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001824 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001825 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001826 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001827 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001828 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001829 /* it is not always needed, but we aim to smaller code */
1830 int squirrel[] = { -1, -1, -1 };
1831 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001832 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001833
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001834 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001835
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001836#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001837 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001838#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001839 pi->alive_cmds = 1;
1840 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001841
1842 /* Check if this is a simple builtin (not part of a pipe).
1843 * Builtins within pipes have to fork anyway, and are handled in
1844 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1845 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001846 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001847
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001848#if ENABLE_HUSH_FUNCTIONS
1849 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
1850 /* We "execute" function definition */
1851 bb_error_msg("here we ought to remember function definition, and go on");
1852 return EXIT_SUCCESS;
1853 }
1854#endif
1855
1856 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00001857 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001858 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001859 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001860 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00001861 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001862 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001863 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00001864 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001865 }
1866
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001867 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001868 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001869
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001870 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001871 char **new_env = NULL;
1872 char **old_env = NULL;
1873
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001874 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001875 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001876 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001877 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001878 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001879 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001880 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001881 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001882 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00001883 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001884
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001885 /* Expand the rest into (possibly) many strings each */
1886 argv_expanded = expand_strvec_to_strvec(argv + i);
1887
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001888 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001889 if (strcmp(argv_expanded[0], x->cmd) != 0)
1890 continue;
1891 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
1892 debug_printf("exec with redirects only\n");
1893 setup_redirects(command, NULL);
1894 rcode = EXIT_SUCCESS;
1895 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00001896 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001897 debug_printf("builtin inline %s\n", argv_expanded[0]);
1898 /* XXX setup_redirects acts on file descriptors, not FILEs.
1899 * This is perfect for work that comes after exec().
1900 * Is it really safe for inline use? Experimentally,
1901 * things seem to work with glibc. */
1902 setup_redirects(command, squirrel);
1903 new_env = expand_assignments(argv, command->assignment_cnt);
1904 old_env = putenv_all_and_save_old(new_env);
1905 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
1906 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001907#if ENABLE_FEATURE_SH_STANDALONE
1908 clean_up_and_ret:
1909#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001910 restore_redirects(squirrel);
1911 free_strings_and_unsetenv(new_env, 1);
1912 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001913 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001914 clean_up_and_ret1:
1915 free(argv_expanded);
1916 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1917 debug_printf_exec("run_pipe return %d\n", rcode);
1918 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00001919 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001920#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00001921 i = find_applet_by_name(argv_expanded[0]);
1922 if (i >= 0 && APPLET_IS_NOFORK(i)) {
1923 setup_redirects(command, squirrel);
1924 save_nofork_data(&G.nofork_save);
1925 new_env = expand_assignments(argv, command->assignment_cnt);
1926 old_env = putenv_all_and_save_old(new_env);
1927 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1928 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
1929 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001930 }
1931#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001932 }
1933
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001934 /* NB: argv_expanded may already be created, and that
1935 * might include `cmd` runs! Do not rerun it! We *must*
1936 * use argv_expanded if it's non-NULL */
1937
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001938 /* Disable job control signals for shell (parent) and
1939 * for initial child code after fork */
1940 set_jobctrl_sighandler(SIG_IGN);
1941
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001942 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001943 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001944 nextin = 0;
1945
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001946 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00001947#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001948 volatile nommu_save_t nommu_save;
1949 nommu_save.new_env = NULL;
1950 nommu_save.old_env = NULL;
1951 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00001952#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001953 command = &(pi->cmds[i]);
1954 if (command->argv) {
1955 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001956 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001957 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001958
1959 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001960 pipefds[0] = 0;
1961 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001962 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001963 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001964
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001965 command->pid = BB_MMU ? fork() : vfork();
1966 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00001967 if (ENABLE_HUSH_JOB)
1968 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001969#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001970 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00001971 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001972 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001973 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001974 /* Don't do pgrp restore anymore on fatal signals */
1975 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001976 pgrp = pi->pgrp;
1977 if (pgrp < 0) /* true for 1st process only */
1978 pgrp = getpid();
1979 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001980 /* We do it in *every* child, not just first,
1981 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001982 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001983 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001984 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001985#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00001986 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001987 xmove_fd(pipefds[1], 1); /* write end */
1988 if (pipefds[0] > 1)
1989 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00001990 /* Like bash, explicit redirects override pipes,
1991 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001992 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001993
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001994 /* Restore default handlers just prior to exec */
1995 set_jobctrl_sighandler(SIG_DFL);
1996 set_misc_sighandler(SIG_DFL);
1997 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001998 /* Stores to nommu_save list of env vars putenv'ed
1999 * (NOMMU, on MMU we don't need that) */
2000 /* cast away volatility... */
2001 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002002 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002003 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002004 /* parent */
2005#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002006 /* Clean up after vforked child */
2007 free(nommu_save.argv);
2008 free_strings_and_unsetenv(nommu_save.new_env, 1);
2009 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002010#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002011 free(argv_expanded);
2012 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002013 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002014 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002015 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002016 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002017 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002018#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002019 /* Second and next children need to know pid of first one */
2020 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002021 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002022#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002023 }
Eric Andersen25f27032001-04-26 23:22:31 +00002024
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002025 if (i)
2026 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002027 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002028 close(pipefds[1]); /* write end */
2029 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002030 nextin = pipefds[0];
2031 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002032
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002033 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002034 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2035 return 1;
2036 }
2037
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002038 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002039 return -1;
2040}
2041
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002042#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002043static void debug_print_tree(struct pipe *pi, int lvl)
2044{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002045 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002046 [PIPE_SEQ] = "SEQ",
2047 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002048 [PIPE_OR ] = "OR" ,
2049 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002050 };
2051 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002052 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002053#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002054 [RES_IF ] = "IF" ,
2055 [RES_THEN ] = "THEN" ,
2056 [RES_ELIF ] = "ELIF" ,
2057 [RES_ELSE ] = "ELSE" ,
2058 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002059#endif
2060#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002061 [RES_FOR ] = "FOR" ,
2062 [RES_WHILE] = "WHILE",
2063 [RES_UNTIL] = "UNTIL",
2064 [RES_DO ] = "DO" ,
2065 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002066#endif
2067#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002068 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002069#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002070#if ENABLE_HUSH_CASE
2071 [RES_CASE ] = "CASE" ,
2072 [RES_MATCH] = "MATCH",
2073 [RES_CASEI] = "CASEI",
2074 [RES_ESAC ] = "ESAC" ,
2075#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002076 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002077 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002078 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002079 static const char *const GRPTYPE[] = {
2080 "()",
2081 "{}",
2082#if ENABLE_HUSH_FUNCTIONS
2083 "func()",
2084#endif
2085 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002086
2087 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002088
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002089 pin = 0;
2090 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002091 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2092 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002093 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002094 while (prn < pi->num_cmds) {
2095 struct command *command = &pi->cmds[prn];
2096 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002097
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002098 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2099 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002100 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002101 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002102 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002103 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002104 prn++;
2105 continue;
2106 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002107 if (argv) while (*argv) {
2108 fprintf(stderr, " '%s'", *argv);
2109 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002110 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002111 fprintf(stderr, "\n");
2112 prn++;
2113 }
2114 pi = pi->next;
2115 pin++;
2116 }
2117}
2118#endif
2119
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002120/* NB: called by pseudo_exec, and therefore must not modify any
2121 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002122static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002123{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002124#if ENABLE_HUSH_CASE
2125 char *case_word = NULL;
2126#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002127#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002128 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002129 char *for_varname = NULL;
2130 char **for_lcur = NULL;
2131 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002132#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002133 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002134 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002135#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002136 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002137#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002138 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002139#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002140 /*enum reserved_style*/ smallint rword = RES_NONE;
2141 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002142
Denis Vlasenko87a86552008-07-29 19:43:10 +00002143 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002144
Denis Vlasenko06810332007-05-21 23:30:54 +00002145#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002146 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002147 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2148 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002149 continue;
2150 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002151 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002152 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002153 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002154 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002155 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002156 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002157 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002158 continue;
2159 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002160 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2161 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002162 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002163 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002164 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002165 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002166 }
2167 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002168#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002169
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002170 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002171 * in order to return, no direct "return" statements please.
2172 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002173
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002174#if ENABLE_HUSH_JOB
2175 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2176 * We are saving state before entering outermost list ("while...done")
2177 * so that ctrl-Z will correctly background _entire_ outermost list,
2178 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002179 if (++G.run_list_level == 1 && G.interactive_fd) {
2180 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002181 /* ctrl-Z forked and we are parent; or ctrl-C.
2182 * Sighandler has longjmped us here */
2183 signal(SIGINT, SIG_IGN);
2184 signal(SIGTSTP, SIG_IGN);
2185 /* Restore level (we can be coming from deep inside
2186 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002187 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002188#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002189 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002190 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002191 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002192 }
2193#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002194 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002195 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2196 * Remember this child as background job */
2197 insert_bg_job(pi);
2198 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002199 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002200 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002201 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002202 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002203 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002204 rcode = 0;
2205 goto ret;
2206 }
2207 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002208 G.toplevel_list = pi;
2209 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002210#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002211 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002212#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002213 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002214 signal(SIGINT, handler_ctrl_c);
2215 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002216#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002217
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002218 /* Go through list of pipes, (maybe) executing them. */
2219 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002220 IF_HAS_KEYWORDS(rword = pi->res_word;)
2221 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002222 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2223 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002224#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002225 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002226 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002227 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002228 /* start of a loop: remember where loop starts */
2229 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002230 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002231 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002232#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002233 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002234 if (pi->followup == PIPE_SEQ)
2235 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002236 /* it is "<false> && CMD" or "<true> || CMD"
2237 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002238 continue;
2239 }
2240 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002241 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002242#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002243 if (cond_code) {
2244 if (rword == RES_THEN) {
2245 /* "if <false> THEN cmd": skip cmd */
2246 continue;
2247 }
2248 } else {
2249 if (rword == RES_ELSE || rword == RES_ELIF) {
2250 /* "if <true> then ... ELSE/ELIF cmd":
2251 * skip cmd and all following ones */
2252 break;
2253 }
2254 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002255#endif
2256#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002257 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002258 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002259 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002260
2261 static const char encoded_dollar_at[] ALIGN1 = {
2262 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2263 }; /* encoded representation of "$@" */
2264 static const char *const encoded_dollar_at_argv[] = {
2265 encoded_dollar_at, NULL
2266 }; /* argv list with one element: "$@" */
2267 char **vals;
2268
2269 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002270 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002271 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002272 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002273 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002274 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002275 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002276 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002277 debug_print_strings("for_list made from", vals);
2278 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002279 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002280 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002281 for_varname = pi->cmds[0].argv[0];
2282 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002283 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002284 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002285 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002286 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002287 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002288 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002289 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002290 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002291 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002292 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002293 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002294//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002295 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2296 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002297 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002298 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002299 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002300 if (rword == RES_DONE) {
2301 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002302 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002303#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002304#if ENABLE_HUSH_CASE
2305 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002306 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002307 continue;
2308 }
2309 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002310 char **argv;
2311
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002312 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2313 break;
2314 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002315 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002316 while (*argv) {
2317 char *pattern = expand_string_to_string(*argv);
2318 /* TODO: which FNM_xxx flags to use? */
2319 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2320 free(pattern);
2321 if (cond_code == 0) { /* match! we will execute this branch */
2322 free(case_word); /* make future "word)" stop */
2323 case_word = NULL;
2324 break;
2325 }
2326 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002327 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002328 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002329 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002330 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002331 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002332 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002333 }
2334#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002335 if (pi->num_cmds == 0)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002336 continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002337
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002338 /* After analyzing all keywords and conditions, we decided
2339 * to execute this pipe. NB: has to do checkjobs(NULL)
2340 * after run_pipe() to collect any background children,
2341 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002342 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002343 {
2344 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002345#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002346 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002347#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002348 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2349 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002350 /* we only ran a builtin: rcode is already known
2351 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002352#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002353 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002354 if (G.flag_break_continue) {
2355 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002356 /* we might fall into outer *loop*,
2357 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002358 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002359 G.depth_break_continue--;
2360 if (G.depth_break_continue == 0)
2361 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002362 /* else: e.g. "continue 2" should *break* once, *then* continue */
2363 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002364 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002365 goto check_jobs_and_break;
2366 /* "continue": simulate end of loop */
2367 rword = RES_DONE;
2368 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002369 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002370#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002371 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002372 /* what does bash do with attempts to background builtins? */
2373 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002374 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2375 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002376#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002377 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002378 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002379#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002380 rcode = 0; /* EXIT_SUCCESS */
2381 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002382#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002383 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002384 /* waits for completion, then fg's main shell */
2385 rcode = checkjobs_and_fg_shell(pi);
2386 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2387 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002388#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002389 { /* this one just waits for completion */
2390 rcode = checkjobs(pi);
2391 debug_printf_exec(": checkjobs returned %d\n", rcode);
2392 }
Eric Andersen25f27032001-04-26 23:22:31 +00002393 }
2394 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002395 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002396 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002397
2398 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002399#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002400 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002401 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002402#endif
2403#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002404 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002405 if (rcode) {
2406 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002407 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002408 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002409 }
2410 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002411 if (!rcode) {
2412 check_jobs_and_break:
2413 checkjobs(NULL);
2414 break;
2415 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002416 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002417#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002418 if ((rcode == 0 && pi->followup == PIPE_OR)
2419 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002420 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002421 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002422 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002423 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002424 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002425
2426#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002427 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002428 /* ctrl-Z forked somewhere in the past, we are the child,
2429 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002430//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002431 exit(rcode);
2432 }
2433 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002434 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002435 signal(SIGTSTP, SIG_IGN);
2436 signal(SIGINT, SIG_IGN);
2437 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002438#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002439 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002440#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002441 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002442 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002443 free(for_list);
2444#endif
2445#if ENABLE_HUSH_CASE
2446 free(case_word);
2447#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002448 return rcode;
2449}
2450
Eric Andersen25f27032001-04-26 23:22:31 +00002451/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002452static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002453{
2454 char **p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002455 struct command *command;
Eric Andersen25f27032001-04-26 23:22:31 +00002456 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002457 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002458
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002459 if (pi->stopped_cmds > 0)
Eric Andersen52a97ca2001-06-22 06:49:26 +00002460 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002461 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002462 for (i = 0; i < pi->num_cmds; i++) {
2463 command = &pi->cmds[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002464 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002465 if (command->argv) {
2466 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002467 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002468 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002469 free_strings(command->argv);
2470 command->argv = NULL;
2471 } else if (command->group) {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002472 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002473 ret_code = free_pipe_list(command->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002474 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002475 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002476 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002477 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002478 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko211b59b2008-06-23 16:28:53 +00002479 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002480 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002481 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002482 if (r->rd_filename) {
2483 debug_printf_clean(" %s\n", r->rd_filename);
2484 free(r->rd_filename);
2485 r->rd_filename = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002486 }
Eric Andersen25f27032001-04-26 23:22:31 +00002487 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002488 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002489 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002490 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002491 free(r);
2492 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002493 command->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002494 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002495 free(pi->cmds); /* children are an array, they get freed all at once */
2496 pi->cmds = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002497#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002498 free(pi->cmdtext);
2499 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002500#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002501 return ret_code;
2502}
2503
Eric Andersenbf7df042001-05-23 22:18:35 +00002504static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002505{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002506 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002507 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002508
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002509 for (pi = head; pi; pi = next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002510#if HAS_KEYWORDS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002511 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002512#endif
Eric Andersenbf7df042001-05-23 22:18:35 +00002513 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002514 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002515 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002516 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002517 free(pi);
2518 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002519 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002520}
2521
2522/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002523static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002524{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002525 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002526 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002527 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002528 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002529 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002530 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002531 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002532 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002533 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002534 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002535 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002536 return rcode;
2537}
2538
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002539
Denis Vlasenko170435c2007-05-23 13:01:10 +00002540/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002541 * all variable references within and returns a pointer to
2542 * a list of expanded strings, possibly with larger number
2543 * of strings. (Think VAR="a b"; echo $VAR).
2544 * This new list is allocated as a single malloc block.
2545 * NULL-terminated list of char* pointers is at the beginning of it,
2546 * followed by strings themself.
2547 * Caller can deallocate entire list by single free(list). */
2548
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002549/* Store given string, finalizing the word and starting new one whenever
Denis Vlasenko87a86552008-07-29 19:43:10 +00002550 * we encounter IFS char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002551 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002552static int expand_on_ifs(o_string *output, int n, const char *str)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002553{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002554 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002555 int word_len = strcspn(str, G.ifs);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002556 if (word_len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002557 if (output->o_quote || !output->o_glob)
2558 o_addQstr(output, str, word_len);
2559 else /* protect backslashes against globbing up :) */
2560 o_addstr_duplicate_backslash(output, str, word_len);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002561 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002562 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002563 if (!*str) /* EOL - do not finalize word */
2564 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002565 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002566 debug_print_list("expand_on_ifs", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002567 n = o_save_ptr(output, n);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002568 str += strspn(str, G.ifs); /* skip ifs chars */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002569 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002570 debug_print_list("expand_on_ifs[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002571 return n;
2572}
2573
2574/* Expand all variable references in given string, adding words to list[]
2575 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2576 * to be filled). This routine is extremely tricky: has to deal with
2577 * variables/parameters with whitespace, $* and $@, and constructs like
2578 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002579static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002580{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002581 /* or_mask is either 0 (normal case) or 0x80
Denis Vlasenko55789c62008-06-18 16:30:42 +00002582 * (expansion of right-hand side of assignment == 1-element expand.
2583 * It will also do no globbing, and thus we must not backslash-quote!) */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002584
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002585 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002586 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002587 const char *val;
2588 char *p;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002589
2590 ored_ch = 0;
2591
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002592 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002593 debug_print_list("expand_vars_to_list", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002594 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002595 debug_print_list("expand_vars_to_list[0]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002596
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002597 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002598#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002599 o_string subst_result = NULL_O_STRING;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002600#endif
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002601 o_addstr(output, arg, p - arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002602 debug_print_list("expand_vars_to_list[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002603 arg = ++p;
2604 p = strchr(p, SPECIAL_VAR_SYMBOL);
2605
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002606 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002607 /* "$@" is special. Even if quoted, it can still
2608 * expand to nothing (not even an empty string) */
2609 if ((first_ch & 0x7f) != '@')
2610 ored_ch |= first_ch;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002611 val = NULL;
2612 switch (first_ch & 0x7f) {
2613 /* Highest bit in first_ch indicates that var is double-quoted */
2614 case '$': /* pid */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002615 val = utoa(G.root_pid);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002616 break;
2617 case '!': /* bg pid */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002618 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002619 break;
2620 case '?': /* exitcode */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002621 val = utoa(G.last_return_code);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002622 break;
2623 case '#': /* argc */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002624 val = utoa(G.global_argc ? G.global_argc-1 : 0);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002625 break;
2626 case '*':
2627 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002628 i = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002629 if (!G.global_argv[i])
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002630 break;
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002631 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002632 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002633 smallint sv = output->o_quote;
2634 /* unquoted var's contents should be globbed, so don't quote */
2635 output->o_quote = 0;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002636 while (G.global_argv[i]) {
2637 n = expand_on_ifs(output, n, G.global_argv[i]);
2638 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2639 if (G.global_argv[i++][0] && G.global_argv[i]) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002640 /* this argv[] is not empty and not last:
2641 * put terminating NUL, start new word */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002642 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002643 debug_print_list("expand_vars_to_list[2]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002644 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002645 debug_print_list("expand_vars_to_list[3]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002646 }
2647 }
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002648 output->o_quote = sv;
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002649 } else
2650 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002651 * and in this case should treat it like '$*' - see 'else...' below */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002652 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002653 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002654 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2655 if (++i >= G.global_argc)
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002656 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002657 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002658 debug_print_list("expand_vars_to_list[4]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002659 n = o_save_ptr(output, n);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002660 }
2661 } else { /* quoted $*: add as one word */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002662 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002663 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2664 if (!G.global_argv[++i])
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002665 break;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002666 if (G.ifs[0])
2667 o_addchr(output, G.ifs[0]);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002668 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002669 }
2670 break;
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002671 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2672 /* "Empty variable", used to make "" etc to not disappear */
2673 arg++;
2674 ored_ch = 0x80;
2675 break;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002676#if ENABLE_HUSH_TICK
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002677 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002678 struct in_str input;
2679 *p = '\0';
2680 arg++;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002681//TODO: can we just stuff it into "output" directly?
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002682 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002683 setup_string_in_str(&input, arg);
2684 process_command_subs(&subst_result, &input, NULL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002685 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002686 val = subst_result.data;
2687 goto store_val;
2688 }
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002689#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002690 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002691 *p = '\0';
2692 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002693 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002694 i = xatoi_u(arg);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002695 if (i < G.global_argc)
2696 val = G.global_argv[i];
Denis Vlasenko55789c62008-06-18 16:30:42 +00002697 /* else val remains NULL: $N with too big N */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002698 } else
2699 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002700 arg[0] = first_ch;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002701#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002702 store_val:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002703#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002704 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002705 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002706 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002707 if (val) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002708 /* unquoted var's contents should be globbed, so don't quote */
2709 smallint sv = output->o_quote;
2710 output->o_quote = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002711 n = expand_on_ifs(output, n, val);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002712 val = NULL;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002713 output->o_quote = sv;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002714 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002715 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002716 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002717 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002718 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002719 if (val) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002720 o_addQstr(output, val, strlen(val));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002721 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002722
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002723#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002724 o_free(&subst_result);
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002725#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002726 arg = ++p;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002727 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2728
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002729 if (arg[0]) {
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002730 debug_print_list("expand_vars_to_list[a]", output, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002731 /* this part is literal, and it was already pre-quoted
2732 * if needed (much earlier), do not use o_addQstr here! */
2733 o_addstr(output, arg, strlen(arg) + 1);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002734 debug_print_list("expand_vars_to_list[b]", output, n);
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002735 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2736 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2737 ) {
2738 n--;
2739 /* allow to reuse list[n] later without re-growth */
2740 output->has_empty_slot = 1;
2741 } else {
2742 o_addchr(output, '\0');
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002743 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002744 return n;
2745}
2746
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002747static char **expand_variables(char **argv, int or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002748{
2749 int n;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002750 char **list;
2751 char **v;
2752 o_string output = NULL_O_STRING;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002753
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002754 if (or_mask & 0x100) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002755 output.o_quote = 1; /* protect against globbing for "$var" */
2756 /* (unquoted $var will temporarily switch it off) */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002757 output.o_glob = 1;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002758 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002759
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002760 n = 0;
2761 v = argv;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002762 while (*v) {
2763 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2764 v++;
2765 }
2766 debug_print_list("expand_variables", &output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002767
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002768 /* output.data (malloced in one block) gets returned in "list" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002769 list = o_finalize_list(&output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002770 debug_print_strings("expand_variables[1]", list);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002771 return list;
2772}
2773
Denis Vlasenko170435c2007-05-23 13:01:10 +00002774static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002775{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002776 return expand_variables(argv, 0x100);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002777}
2778
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002779/* Used for expansion of right hand of assignments */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002780/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2781 * "v=/bin/c*" */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002782static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002783{
2784 char *argv[2], **list;
2785
2786 argv[0] = (char*)str;
2787 argv[1] = NULL;
2788 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002789 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002790 if (!list[0] || list[1])
2791 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002792 /* actually, just move string 2*sizeof(char*) bytes back */
2793 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002794 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2795 return (char*)list;
2796}
2797
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002798/* Used for "eval" builtin */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002799static char* expand_strvec_to_string(char **argv)
2800{
2801 char **list;
2802
2803 list = expand_variables(argv, 0x80);
2804 /* Convert all NULs to spaces */
2805 if (list[0]) {
2806 int n = 1;
2807 while (list[n]) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002808 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002809 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2810 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002811 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002812 n++;
2813 }
2814 }
2815 strcpy((char*)list, list[0]);
2816 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002817 return (char*)list;
2818}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002819
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002820
2821/* Used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002822static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002823{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002824 struct variable *cur;
2825 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002826
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002827 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002828 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002829 len = strlen(name);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002830 for (cur = G.top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002831 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002832 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002833 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002834 return NULL;
2835}
2836
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002837/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002838 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002839static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002840{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002841 struct variable *cur;
2842 char *value;
2843 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002844
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002845 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002846 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002847 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002848 return -1;
2849 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002850
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002851 name_len = value - str + 1; /* including '=' */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002852 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002853 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002854 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002855 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002856 /* Bail out. Note that now cur points
2857 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002858 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002859 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002860 cur = cur->next;
2861 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002862 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002863 /* We found an existing var with this name */
2864 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002865 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002866 bb_error_msg("%s: readonly variable", str);
2867 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002868 return -1;
2869 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002870 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002871 unsetenv(str); /* just in case */
2872 *value = '=';
2873 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002874 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002875 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002876 goto exp;
2877 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002878 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002879 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002880 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002881 goto free_and_exp;
2882 }
2883 /* max_len == 0 signifies "malloced" var, which we can
2884 * (and has to) free */
2885 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002886 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002887 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002888 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002889 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002890
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002891 /* Not found - create next variable struct */
2892 cur->next = xzalloc(sizeof(*cur));
2893 cur = cur->next;
2894
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002895 set_str_and_exp:
2896 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002897 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002898 if (flg_export)
2899 cur->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002900 if (cur->flg_export) {
2901 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002902 return putenv(cur->varstr);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002903 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002904 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002905}
2906
Eric Andersenf72f5622001-05-15 23:21:41 +00002907static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002908{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002909 struct variable *cur;
2910 struct variable *prev = prev; /* for gcc */
2911 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002912
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002913 if (!name)
2914 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002915 name_len = strlen(name);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002916 cur = G.top_var;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002917 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002918 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002919 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002920 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002921 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002922 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002923 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2924 * is ro, and we cannot reach this code on the 1st pass */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002925 prev->next = cur->next;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002926 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002927 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002928 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002929 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002930 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002931 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002932 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002933 prev = cur;
2934 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002935 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002936}
2937
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002938/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00002939 * for file descriptor duplication, e.g., "2>&1".
2940 * Return code is 0 normally, 1 if a syntax error is detected in src.
2941 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002942static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00002943 struct in_str *input)
2944{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002945 struct command *command = ctx->command;
2946 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002947 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002948
2949 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002950 while (redir) {
2951 last_redir = redir;
2952 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002953 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002954 redir = xzalloc(sizeof(struct redir_struct));
2955 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002956 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002957 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002958 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002959 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002960 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002961 }
2962
Denis Vlasenko55789c62008-06-18 16:30:42 +00002963 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002964 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002965
2966 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2967
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002968 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002969 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002970 if (redir->dup == -2)
2971 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002972 if (redir->dup != -1) {
2973 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002974 * is legit; I postpone that to "run time"
2975 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002976 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2977 } else {
2978 /* We do _not_ try to open the file that src points to,
2979 * since we need to return and let src be expanded first.
2980 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002981 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002982 ctx->pending_redirect = redir;
2983 }
2984 return 0;
2985}
2986
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002987static struct pipe *new_pipe(void)
2988{
Eric Andersen25f27032001-04-26 23:22:31 +00002989 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002990 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002991 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002992 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002993 return pi;
2994}
2995
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002996static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002997{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002998 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002999 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003000 /* Create the memory for command, roughly:
3001 * ctx->pipe->cmds = new struct command;
3002 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003003 */
3004 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003005}
3006
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003007/* If a reserved word is found and processed, parse context is modified
3008 * and 1 is returned.
3009 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003010 * case, function, and select are obnoxious, save those for later.
3011 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003012#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003013struct reserved_combo {
3014 char literal[6];
3015 unsigned char res;
3016 unsigned char assignment_flag;
3017 int flag;
3018};
3019enum {
3020 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003021#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003022 FLAG_IF = (1 << RES_IF ),
3023 FLAG_THEN = (1 << RES_THEN ),
3024 FLAG_ELIF = (1 << RES_ELIF ),
3025 FLAG_ELSE = (1 << RES_ELSE ),
3026 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003027#endif
3028#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003029 FLAG_FOR = (1 << RES_FOR ),
3030 FLAG_WHILE = (1 << RES_WHILE),
3031 FLAG_UNTIL = (1 << RES_UNTIL),
3032 FLAG_DO = (1 << RES_DO ),
3033 FLAG_DONE = (1 << RES_DONE ),
3034 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003035#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003036#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003037 FLAG_MATCH = (1 << RES_MATCH),
3038 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003039#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003040 FLAG_START = (1 << RES_XXXX ),
3041};
3042
3043static const struct reserved_combo* match_reserved_word(o_string *word)
3044{
Eric Andersen25f27032001-04-26 23:22:31 +00003045 /* Mostly a list of accepted follow-up reserved words.
3046 * FLAG_END means we are done with the sequence, and are ready
3047 * to turn the compound list into a command.
3048 * FLAG_START means the word must start a new compound list.
3049 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003050 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003051#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003052 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3053 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3054 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3055 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3056 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3057 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003058#endif
3059#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003060 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3061 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3062 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3063 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3064 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3065 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003066#endif
3067#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003068 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3069 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003070#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003071 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003072 const struct reserved_combo *r;
3073
3074 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3075 if (strcmp(word->data, r->literal) == 0)
3076 return r;
3077 }
3078 return NULL;
3079}
3080static int reserved_word(o_string *word, struct parse_context *ctx)
3081{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003082#if ENABLE_HUSH_CASE
3083 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003084 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003085 };
3086#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003087 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003088
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003089 r = match_reserved_word(word);
3090 if (!r)
3091 return 0;
3092
3093 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003094#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003095 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3096 /* "case word IN ..." - IN part starts first match part */
3097 r = &reserved_match;
3098 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003099#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003100 if (r->flag == 0) { /* '!' */
3101 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003102 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003103 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003104 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003105 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003106 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003107 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003108 if (r->flag & FLAG_START) {
3109 struct parse_context *new;
3110 debug_printf("push stack\n");
3111 new = xmalloc(sizeof(*new));
3112 *new = *ctx; /* physical copy */
3113 initialize_context(ctx);
3114 ctx->stack = new;
3115 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3116 syntax(NULL);
3117 ctx->ctx_res_w = RES_SNTX;
3118 return 1;
3119 }
3120 ctx->ctx_res_w = r->res;
3121 ctx->old_flag = r->flag;
3122 if (ctx->old_flag & FLAG_END) {
3123 struct parse_context *old;
3124 debug_printf("pop stack\n");
3125 done_pipe(ctx, PIPE_SEQ);
3126 old = ctx->stack;
3127 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003128 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003129 *ctx = *old; /* physical copy */
3130 free(old);
3131 }
3132 word->o_assignment = r->assignment_flag;
3133 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003134}
Denis Vlasenko06810332007-05-21 23:30:54 +00003135#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003136
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003137//TODO: many, many callers don't check error from done_word()
3138
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003139/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003140 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003141static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003142{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003143 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003144
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003145 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003146 if (word->length == 0 && word->nonnull == 0) {
3147 debug_printf_parse("done_word return 0: true null, ignored\n");
3148 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003149 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003150 /* If this word wasn't an assignment, next ones definitely
3151 * can't be assignments. Even if they look like ones. */
3152 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3153 && word->o_assignment != WORD_IS_KEYWORD
3154 ) {
3155 word->o_assignment = NOT_ASSIGNMENT;
3156 } else {
3157 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003158 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003159 word->o_assignment = MAYBE_ASSIGNMENT;
3160 }
3161
Eric Andersen25f27032001-04-26 23:22:31 +00003162 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003163 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3164 * only if run as "bash", not "sh" */
3165 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003166 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003167 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003168 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003169 /* "{ echo foo; } echo bar" - bad */
3170 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003171 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003172 syntax(NULL);
3173 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3174 return 1;
3175 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003176#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003177#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003178 if (ctx->ctx_dsemicolon
3179 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3180 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003181 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003182 /* ctx->ctx_res_w = RES_MATCH; */
3183 ctx->ctx_dsemicolon = 0;
3184 } else
3185#endif
3186
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003187 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003188#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003189 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3190 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003191#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003192 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003193 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3194 if (reserved_word(word, ctx)) {
3195 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003196 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3197 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003198 }
Eric Andersen25f27032001-04-26 23:22:31 +00003199 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003200#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003201 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003202 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3203 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003204 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003205 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003206 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003207 char *p = word->data;
3208 while (p[0] == SPECIAL_VAR_SYMBOL
3209 && (p[1] & 0x7f) == '@'
3210 && p[2] == SPECIAL_VAR_SYMBOL
3211 ) {
3212 p += 3;
3213 }
3214 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003215 /* saw no "$@", or not only "$@" but some
3216 * real text is there too */
3217 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003218 * e.g. "", $empty"" etc to not disappear */
3219 o_addchr(word, SPECIAL_VAR_SYMBOL);
3220 o_addchr(word, SPECIAL_VAR_SYMBOL);
3221 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003222 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003223 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003224 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003225 }
Eric Andersen25f27032001-04-26 23:22:31 +00003226
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003227 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003228 ctx->pending_redirect = NULL;
3229
Denis Vlasenko06810332007-05-21 23:30:54 +00003230#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003231 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003232 /* NB: basically, this makes hush see "for v in ..." syntax as if
3233 * as it is "for v; in ...". FOR and IN become two pipe structs
3234 * in parse tree. */
3235 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003236//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003237 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003238 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003239#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003240#if ENABLE_HUSH_CASE
3241 /* Force CASE to have just one word */
3242 if (ctx->ctx_res_w == RES_CASE) {
3243 done_pipe(ctx, PIPE_SEQ);
3244 }
3245#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003246 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003247 return 0;
3248}
3249
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003250/* Command (member of a pipe) is complete. The only possible error here
3251 * is out of memory, in which case xmalloc exits. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003252static int done_command(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003253{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003254 /* The command is really already in the pipe structure, so
3255 * advance the pipe counter and make a new, null command. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003256 struct pipe *pi = ctx->pipe;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003257 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003258
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003259 if (command) {
3260 if (command->group == NULL
3261 && command->argv == NULL
3262 && command->redirects == NULL
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003263 ) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003264 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3265 return pi->num_cmds;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003266 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003267 pi->num_cmds++;
3268 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003269 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003270 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003271 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003272
3273 /* Only real trickiness here is that the uncommitted
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003274 * command structure is not counted in pi->num_cmds. */
3275 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3276 command = &pi->cmds[pi->num_cmds];
3277 memset(command, 0, sizeof(*command));
Eric Andersen25f27032001-04-26 23:22:31 +00003278
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003279 ctx->command = command;
Eric Andersen25f27032001-04-26 23:22:31 +00003280 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003281
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003282 return pi->num_cmds; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003283}
3284
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003285static void done_pipe(struct parse_context *ctx, pipe_style type)
Eric Andersen25f27032001-04-26 23:22:31 +00003286{
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003287 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003288
3289 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenko395ae452008-07-14 06:29:38 +00003290 /* Close previous command */
3291 not_null = done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003292 ctx->pipe->followup = type;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003293 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3294 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003295 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
Denis Vlasenko395ae452008-07-14 06:29:38 +00003296
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003297 /* Without this check, even just <enter> on command line generates
3298 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003299 * IOW: it is safe to do it unconditionally.
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003300 * RES_NONE case is for "for a in; do ..." (empty IN set)
3301 * to work, possibly other cases too. */
3302 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003303 struct pipe *new_p;
3304 debug_printf_parse("done_pipe: adding new pipe: "
Denis Vlasenko757361f2008-07-14 08:26:47 +00003305 "not_null:%d ctx->ctx_res_w:%d\n",
Denis Vlasenko395ae452008-07-14 06:29:38 +00003306 not_null, ctx->ctx_res_w);
3307 new_p = new_pipe();
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003308 ctx->pipe->next = new_p;
3309 ctx->pipe = new_p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003310 ctx->command = NULL; /* needed! */
Denis Vlasenko395ae452008-07-14 06:29:38 +00003311 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003312 * they remain set for commands inside if/while.
3313 * This is used to control execution.
3314 * RES_FOR and RES_IN are NOT sticky (needed to support
3315 * cases where variable or value happens to match a keyword):
3316 */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003317#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003318 if (ctx->ctx_res_w == RES_FOR
3319 || ctx->ctx_res_w == RES_IN)
3320 ctx->ctx_res_w = RES_NONE;
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003321#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003322#if ENABLE_HUSH_CASE
3323 if (ctx->ctx_res_w == RES_MATCH)
3324 ctx->ctx_res_w = RES_CASEI;
3325#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003326 /* Create the memory for command, roughly:
3327 * ctx->pipe->cmds = new struct command;
3328 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003329 */
3330 done_command(ctx);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003331 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003332 debug_printf_parse("done_pipe return\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003333}
3334
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003335/* Peek ahead in the in_str to find out if we have a "&n" construct,
Eric Andersen25f27032001-04-26 23:22:31 +00003336 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003337 * Return either -2 (syntax error), -1 (no &), or the number found.
Eric Andersen25f27032001-04-26 23:22:31 +00003338 */
3339static int redirect_dup_num(struct in_str *input)
3340{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003341 int ch, d = 0, ok = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003342 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003343 if (ch != '&') return -1;
3344
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003345 i_getch(input); /* get the & */
3346 ch = i_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003347 if (ch == '-') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003348 i_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003349 return -3; /* "-" represents "close me" */
3350 }
3351 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003352 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003353 ok = 1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003354 i_getch(input);
3355 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003356 }
3357 if (ok) return d;
3358
Manuel Novoa III cad53642003-03-19 09:13:01 +00003359 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003360 return -2;
3361}
3362
3363/* If a redirect is immediately preceded by a number, that number is
3364 * supposed to tell which file descriptor to redirect. This routine
3365 * looks for such preceding numbers. In an ideal world this routine
3366 * needs to handle all the following classes of redirects...
3367 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3368 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3369 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3370 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3371 * A -1 output from this program means no valid number was found, so the
3372 * caller should use the appropriate default for this redirection.
3373 */
3374static int redirect_opt_num(o_string *o)
3375{
3376 int num;
3377
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003378 if (o->length == 0)
3379 return -1;
3380 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003381 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003382 return -1;
3383 }
3384 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003385 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003386 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003387 return num;
3388}
3389
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003390#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003391static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003392{
3393 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003394 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003395
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003396 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003397/* *** NOMMU WARNING *** */
3398/* By using vfork here, we suspend parent till child exits or execs.
3399 * If child will not do it before it fills the pipe, it can block forever
3400 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003401 * Try this script:
3402 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3403 * huge=`cat TESTFILE` # will block here forever
3404 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003405 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003406 pid = BB_MMU ? fork() : vfork();
3407 if (pid < 0)
3408 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003409 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003410 if (ENABLE_HUSH_JOB)
3411 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003412 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003413 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003414 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003415#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003416 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003417#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003418 /* Process substitution is not considered to be usual
3419 * 'command execution'.
3420 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3421 /* Not needed, we are relying on it being disabled
3422 * everywhere outside actual command execution. */
3423 /*set_jobctrl_sighandler(SIG_IGN);*/
3424 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003425 /* Freeing 'head' here would break NOMMU. */
3426 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003427 }
Eric Andersen25f27032001-04-26 23:22:31 +00003428 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003429 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003430 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003431 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003432}
3433
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003434/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003435static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003436 struct in_str *input,
3437 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003438{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003439 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003440 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003441 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003442 FILE *p;
3443 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003444
Eric Andersen25f27032001-04-26 23:22:31 +00003445 initialize_context(&inner);
3446
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003447 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003448 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003449 if (retcode != 0)
3450 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003451 done_word(&result, &inner);
3452 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003453 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003454
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003455 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003456 if (p == NULL)
3457 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003458 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003459 setup_file_in_str(&pipe_str, p);
3460
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003461 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003462 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003463 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003464 if (ch == '\n') {
3465 eol_cnt++;
3466 continue;
3467 }
3468 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003469 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003470 eol_cnt--;
3471 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003472 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003473 }
3474
3475 debug_printf("done reading from pipe, pclose()ing\n");
3476 /* This is the step that wait()s for the child. Should be pretty
3477 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003478 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003479 * at the same time. That would be a lot of work, and contrary
3480 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003481 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003482 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003483 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003484 return retcode;
3485}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003486#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003487
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003488static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003489 struct in_str *input, int ch)
3490{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003491 /* dest contains characters seen prior to ( or {.
3492 * Typically it's empty, but for functions defs,
3493 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003494 int rcode;
3495 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003496 struct parse_context sub;
3497 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003498
3499 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003500#if ENABLE_HUSH_FUNCTIONS
3501 if (ch == 'F') { /* function definition? */
3502 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3503 //command->fname = dest->data;
3504 command->grp_type = GRP_FUNCTION;
3505//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3506 memset(dest, 0, sizeof(*dest));
3507 }
3508#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003509 if (command->argv /* word [word](... */
3510 || dest->length /* word(... */
3511 || dest->nonnull /* ""(... */
3512 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003513 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003514 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3515 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003516 }
3517 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003518 endch = "}";
3519 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003520 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003521 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003522 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003523 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003524 if (rcode == 0) {
3525 done_word(dest, &sub); /* finish off the final word in the subcontext */
3526 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003527 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003528 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003529 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003530 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003531 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003532}
3533
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003534/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003535 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003536static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003537{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003538 struct variable *var = get_local_var(src);
3539 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003540 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003541 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003542}
3543
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003544#if ENABLE_HUSH_TICK
3545/* Subroutines for copying $(...) and `...` things */
3546static void add_till_backquote(o_string *dest, struct in_str *input);
3547/* '...' */
3548static void add_till_single_quote(o_string *dest, struct in_str *input)
3549{
3550 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003551 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003552 if (ch == EOF)
3553 break;
3554 if (ch == '\'')
3555 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003556 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003557 }
3558}
3559/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3560static void add_till_double_quote(o_string *dest, struct in_str *input)
3561{
3562 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003563 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003564 if (ch == '"')
3565 break;
3566 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003567 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003568 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003569 }
3570 if (ch == EOF)
3571 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003572 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003573 if (ch == '`') {
3574 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003575 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003576 continue;
3577 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003578 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003579 }
3580}
3581/* Process `cmd` - copy contents until "`" is seen. Complicated by
3582 * \` quoting.
3583 * "Within the backquoted style of command substitution, backslash
3584 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3585 * The search for the matching backquote shall be satisfied by the first
3586 * backquote found without a preceding backslash; during this search,
3587 * if a non-escaped backquote is encountered within a shell comment,
3588 * a here-document, an embedded command substitution of the $(command)
3589 * form, or a quoted string, undefined results occur. A single-quoted
3590 * or double-quoted string that begins, but does not end, within the
3591 * "`...`" sequence produces undefined results."
3592 * Example Output
3593 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3594 */
3595static void add_till_backquote(o_string *dest, struct in_str *input)
3596{
3597 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003598 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003599 if (ch == '`')
3600 break;
3601 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003602 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003603 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003604 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003605 ch = ch2;
3606 }
3607 if (ch == EOF)
3608 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003609 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003610 }
3611}
3612/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3613 * quoting and nested ()s.
3614 * "With the $(command) style of command substitution, all characters
3615 * following the open parenthesis to the matching closing parenthesis
3616 * constitute the command. Any valid shell script can be used for command,
3617 * except a script consisting solely of redirections which produces
3618 * unspecified results."
3619 * Example Output
3620 * echo $(echo '(TEST)' BEST) (TEST) BEST
3621 * echo $(echo 'TEST)' BEST) TEST) BEST
3622 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3623 */
3624static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3625{
3626 int count = 0;
3627 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003628 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003629 if (ch == EOF)
3630 break;
3631 if (ch == '(')
3632 count++;
3633 if (ch == ')')
3634 if (--count < 0)
3635 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003636 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003637 if (ch == '\'') {
3638 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003639 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003640 continue;
3641 }
3642 if (ch == '"') {
3643 add_till_double_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 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003647 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3648 ch = i_getch(input);
3649 if (ch == EOF)
3650 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003651 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003652 continue;
3653 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003654 }
3655}
3656#endif /* ENABLE_HUSH_TICK */
3657
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003658/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003659static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003660{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003661 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003662 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003663
3664 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003665 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003666 i_getch(input);
3667 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003668 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003669 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003670 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003671 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003672 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003673 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003674 if (!isalnum(ch) && ch != '_')
3675 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003676 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003677 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003678 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003679 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003680 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003681 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003682 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003683 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003684 o_addchr(dest, ch | quote_mask);
3685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003686 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003687 case '$': /* pid */
3688 case '!': /* last bg pid */
3689 case '?': /* last exit code */
3690 case '#': /* number of args */
3691 case '*': /* args */
3692 case '@': /* args */
3693 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003694 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003695 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3696 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003697 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003698 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003699 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003700 if (ch == '}')
3701 break;
3702 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003703 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003704 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3705 return 1;
3706 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003707 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003708 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003709 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003710 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003711 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003712 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003713#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003714 case '(': {
3715 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003716 i_getch(input);
3717 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3718 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003719 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003720 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003721 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003722 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003723 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003724#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003725 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003726 i_getch(input);
3727 ch = i_peek(input);
3728 if (isalnum(ch)) { /* it's $_name or $_123 */
3729 ch = '_';
3730 goto make_var;
3731 }
3732 /* else: it's $_ */
3733 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003734 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003735 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003736 return 1;
3737 break;
3738 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003739 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003740 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003741 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003742 return 0;
3743}
3744
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003745/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003746 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3747 * Return code is 0 if end_trigger char is met,
3748 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003749 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003750static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003751 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003752{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003753 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003754 int redir_fd;
3755 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003756 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003757 int next;
3758
Denis Vlasenkoff097622007-10-01 10:00:45 +00003759 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003760 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003761 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003762
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003763 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 +00003764
Denis Vlasenko1a735862007-05-23 00:32:25 +00003765 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003766 m = CHAR_IFS;
3767 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003768 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003769 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003770 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003771 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003772 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003773 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003774 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003775 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003776 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003777 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003778 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003779 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003780 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003781 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003782 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3783 return 1;
3784 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003785 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003786 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3787 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003788 && ch == '='
3789 && is_assignment(dest->data)
3790 ) {
3791 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3792 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003793 continue;
3794 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003795 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003796 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003797 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003798 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003799 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003800 if (ch == EOF)
3801 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003802 /* If we aren't performing a substitution, treat
3803 * a newline as a command separator.
3804 * [why we don't handle it exactly like ';'? --vda] */
3805 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003806#if ENABLE_HUSH_CASE
3807 /* "case ... in <newline> word) ..." -
3808 * newlines are ignored (but ';' wouldn't be) */
3809 if (dest->length == 0 // && argv[0] == NULL
3810 && ctx->ctx_res_w == RES_MATCH
3811 ) {
3812 continue;
3813 }
3814#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003815 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003816 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003817 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003818 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003819 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003820 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003821 /* Special case: (...word) makes last word terminate,
3822 * as if ';' is seen */
3823 if (ch == ')') {
3824 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003825//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003826 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003827 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003828 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003829 if (!HAS_KEYWORDS
3830 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3831 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003832 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3833 return 0;
3834 }
3835 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003836 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003837 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003838 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003839
3840 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3841 /* ch is a special char and thus this word
3842 * cannot be an assignment: */
3843 dest->o_assignment = NOT_ASSIGNMENT;
3844 }
3845
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003846 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003847 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003848 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003849 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003850 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003851 if (ch == EOF || ch == '\n')
3852 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003853 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003854 }
Eric Andersen25f27032001-04-26 23:22:31 +00003855 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003856 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003857 }
3858 break;
3859 case '\\':
3860 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003861 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003862 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003863 return 1;
3864 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003865 /* bash:
3866 * "The backslash retains its special meaning [in "..."]
3867 * only when followed by one of the following characters:
3868 * $, `, ", \, or <newline>. A double quote may be quoted
3869 * within double quotes by preceding it with a backslash.
3870 * If enabled, history expansion will be performed unless
3871 * an ! appearing in double quotes is escaped using
3872 * a backslash. The backslash preceding the ! is not removed."
3873 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003874 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003875 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003876 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003877 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003878 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003879 }
3880 } else {
3881 o_addchr(dest, '\\');
3882 o_addchr(dest, i_getch(input));
3883 }
Eric Andersen25f27032001-04-26 23:22:31 +00003884 break;
3885 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003886 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003887 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3888 return 1;
3889 }
Eric Andersen25f27032001-04-26 23:22:31 +00003890 break;
3891 case '\'':
3892 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003893 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003894 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003895 if (ch == EOF) {
3896 syntax("unterminated '");
3897 debug_printf_parse("parse_stream return 1: unterminated '\n");
3898 return 1;
3899 }
3900 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003901 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003902 if (dest->o_assignment == NOT_ASSIGNMENT)
3903 o_addqchr(dest, ch);
3904 else
3905 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003906 }
Eric Andersen25f27032001-04-26 23:22:31 +00003907 break;
3908 case '"':
3909 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003910 shadow_quote ^= 1; /* invert */
3911 if (dest->o_assignment == NOT_ASSIGNMENT)
3912 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003913 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003914#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003915 case '`': {
3916 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003917 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003918 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003919 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003920 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003921 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003922 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003923 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003924#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003925 case '>':
3926 redir_fd = redirect_opt_num(dest);
3927 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003928 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003929 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003930 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003931 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003932 }
3933#if 0
3934 else if (next == '(') {
3935 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003936 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003937 return 1;
3938 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003939#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003940 setup_redirect(ctx, redir_fd, redir_style, input);
3941 break;
3942 case '<':
3943 redir_fd = redirect_opt_num(dest);
3944 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003945 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003946 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003947 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003948 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003949 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003950 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003951 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003952 }
3953#if 0
3954 else if (next == '(') {
3955 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003956 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003957 return 1;
3958 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003959#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003960 setup_redirect(ctx, redir_fd, redir_style, input);
3961 break;
3962 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003963#if ENABLE_HUSH_CASE
3964 case_semi:
3965#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003966 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003967 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003968#if ENABLE_HUSH_CASE
3969 /* Eat multiple semicolons, detect
3970 * whether it means something special */
3971 while (1) {
3972 ch = i_peek(input);
3973 if (ch != ';')
3974 break;
3975 i_getch(input);
3976 if (ctx->ctx_res_w == RES_CASEI) {
3977 ctx->ctx_dsemicolon = 1;
3978 ctx->ctx_res_w = RES_MATCH;
3979 break;
3980 }
3981 }
3982#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003983 new_cmd:
3984 /* We just finished a cmd. New one may start
3985 * with an assignment */
3986 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00003987 break;
3988 case '&':
3989 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003990 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003991 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003992 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003993 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003994 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003995 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003996 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00003997 case '|':
3998 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003999#if ENABLE_HUSH_CASE
4000 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00004001 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00004002#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004003 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004004 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004005 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00004006 } else {
4007 /* we could pick up a file descriptor choice here
4008 * with redirect_opt_num(), but bash doesn't do it.
4009 * "echo foo 2| cat" yields "foo 2". */
4010 done_command(ctx);
4011 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004012 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004013 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004014#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00004015 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004016 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004017 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004018 && dest->length == 0 /* not word(... */
4019 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004020 ) {
4021 continue;
4022 }
4023#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004024#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004025 if (dest->length != 0 /* not just () but word() */
4026 && dest->nonnull == 0 /* not a"b"c() */
4027 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004028//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004029 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004030 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004031 ) {
4032 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004033 i_getch(input);
4034 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004035//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004036 ch = i_getch(input);
4037 } while (ch == ' ' || ch == '\n');
4038 if (ch != '{') {
4039 syntax("was expecting {");
4040 debug_printf_parse("parse_stream return 1\n");
4041 return 1;
4042 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004043 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004044 }
4045#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004046 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004047 if (parse_group(dest, ctx, input, ch) != 0) {
4048 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004049 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004050 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004051 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004052 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004053#if ENABLE_HUSH_CASE
4054 if (ctx->ctx_res_w == RES_MATCH)
4055 goto case_semi;
4056#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004057 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004058 /* proper use of this character is caught by end_trigger:
4059 * if we see {, we call parse_group(..., end_trigger='}')
4060 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004061 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004062 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004063 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004064 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004065 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004066 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004067 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004068 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004069 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004070 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004071 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004072 return 0;
4073}
4074
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004075static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004076{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004077 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004078 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004079}
4080
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004081static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004082{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004083 G.ifs = getenv("IFS");
4084 if (G.ifs == NULL)
4085 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004086 /* Precompute a list of 'flow through' behavior so it can be treated
4087 * quickly up front. Computation is necessary because of IFS.
4088 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004089 * The charmap[] array only really needs two bits each,
4090 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004091 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004092 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004093#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004094 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004095#else
4096 set_in_charmap("\\$\"", CHAR_SPECIAL);
4097#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004098 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004099 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004100}
4101
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004102/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004103 * from builtin_source() and builtin_eval() */
4104static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004105{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004106 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004107 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004108 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004109
Eric Andersen25f27032001-04-26 23:22:31 +00004110 do {
4111 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004112 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004113#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004114 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004115#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004116 /* We will stop & execute after each ';' or '\n'.
4117 * Example: "sleep 9999; echo TEST" + ctrl-C:
4118 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004119 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004120 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004121#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004122 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004123 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004124 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004125#endif
4126 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004127 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004128 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004129 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004130 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4131 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004132 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004133 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004134#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004135 if (ctx.old_flag != 0) {
4136 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004137 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004138 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004139#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004140 /*temp.nonnull = 0; - o_free does it below */
4141 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004142 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004143 /* Discard all unprocessed line input, force prompt on */
4144 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004145#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004146 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004147#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004148 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004149 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004150 /* loop on syntax errors, return on EOF: */
4151 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004152 return 0;
4153}
4154
Denis Vlasenko170435c2007-05-23 13:01:10 +00004155static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004156{
4157 struct in_str input;
4158 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004159 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004160}
4161
Denis Vlasenko170435c2007-05-23 13:01:10 +00004162static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004163{
4164 int rcode;
4165 struct in_str input;
4166 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004167 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004168 return rcode;
4169}
4170
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004171#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004172/* Make sure we have a controlling tty. If we get started under a job
4173 * aware app (like bash for example), make sure we are now in charge so
4174 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004175static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004176{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004177 pid_t shell_pgrp;
4178
Denis Vlasenko87a86552008-07-29 19:43:10 +00004179 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004180 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004181
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004182 /* If we were ran as 'hush &',
4183 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004184 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004185 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004186 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004187 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004188 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004189
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004190 /* Ignore job-control and misc signals. */
4191 set_jobctrl_sighandler(SIG_IGN);
4192 set_misc_sighandler(SIG_IGN);
4193//huh? signal(SIGCHLD, SIG_IGN);
4194
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004195 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004196 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004197
4198 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004199 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004200 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004201 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004202}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004203#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004204
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004205
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004206int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004207int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004208{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004209 static const struct variable const_shell_ver = {
4210 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004211 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004212 .max_len = 1, /* 0 can provoke free(name) */
4213 .flg_export = 1,
4214 .flg_read_only = 1,
4215 };
4216
Eric Andersen25f27032001-04-26 23:22:31 +00004217 int opt;
4218 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004219 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004220 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004221
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004222 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004223
Denis Vlasenko87a86552008-07-29 19:43:10 +00004224 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004225
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004226 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004227 G.shell_ver = const_shell_ver; /* copying struct here */
4228 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004229 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004230 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4231 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004232 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004233 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004234 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004235 if (e) while (*e) {
4236 char *value = strchr(*e, '=');
4237 if (value) { /* paranoia */
4238 cur_var->next = xzalloc(sizeof(*cur_var));
4239 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004240 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004241 cur_var->max_len = strlen(*e);
4242 cur_var->flg_export = 1;
4243 }
4244 e++;
4245 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004246 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004247 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004248
Denis Vlasenko38f63192007-01-22 09:03:07 +00004249#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004250 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004251#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004252 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004253 G.global_argc = argc;
4254 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004255 /* Initialize some more globals to non-zero values */
4256 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004257#if ENABLE_HUSH_INTERACTIVE
4258#if ENABLE_FEATURE_EDITING
4259 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004260#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004261 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004262#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004263
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004264 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004265 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004266
4267 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004268 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004269 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004270 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004271 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004272 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004273 fclose(input);
4274 }
Eric Andersen25f27032001-04-26 23:22:31 +00004275 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004276 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004277
Eric Andersen25f27032001-04-26 23:22:31 +00004278 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4279 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004280 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004281 G.global_argv = argv + optind;
4282 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004283 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004284 goto final_return;
4285 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004286 /* Well, we cannot just declare interactiveness,
4287 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004288 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004289 break;
4290 case 'f':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004291 G.fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004292 break;
4293 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004294#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004295 fprintf(stderr, "Usage: sh [FILE]...\n"
4296 " or: sh -c command [args]...\n\n");
4297 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004298#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004299 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004300#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004301 }
4302 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004303#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004304 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004305 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004306 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004307 * no arguments remaining or the -s flag given
4308 * standard input is a terminal
4309 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004310 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004311 if (argv[optind] == NULL && input == stdin
4312 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4313 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004314 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4315 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4316 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004317 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004318 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4319 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004320 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004321 G.interactive_fd = dup(STDIN_FILENO);
4322 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004323 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004324 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004325 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004326 // TODO: track & disallow any attempts of user
4327 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004328 }
Eric Andersen25f27032001-04-26 23:22:31 +00004329 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004330 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4331 if (G.interactive_fd) {
4332 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004333 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004334 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004335 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004336 * (we reset die_sleep = 0 whereever we [v]fork) */
4337 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004338 if (setjmp(die_jmp)) {
4339 /* xfunc has failed! die die die */
4340 hush_exit(xfunc_error_retval);
4341 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004342#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00004343 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004344 printf("Enter 'help' for a list of built-in commands.\n\n");
4345#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004346 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004347#elif ENABLE_HUSH_INTERACTIVE
4348/* no job control compiled, only prompt/line editing */
4349 if (argv[optind] == NULL && input == stdin
4350 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4351 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004352 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4353 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004354 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004355 G.interactive_fd = dup(STDIN_FILENO);
4356 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004357 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004358 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004359 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004360 if (G.interactive_fd) {
4361 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004362 set_misc_sighandler(SIG_IGN);
4363 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004364 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004365#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004366
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004367 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004368 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004369 } else {
4370 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004371 G.global_argv = argv + optind;
4372 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004373 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004374 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004375 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004376 }
Eric Andersen25f27032001-04-26 23:22:31 +00004377
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004378 final_return:
4379
Denis Vlasenko38f63192007-01-22 09:03:07 +00004380#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004381 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004382 if (G.cwd != bb_msg_unknown)
4383 free((char*)G.cwd);
4384 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004385 while (cur_var) {
4386 struct variable *tmp = cur_var;
4387 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004388 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004389 cur_var = cur_var->next;
4390 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004391 }
Eric Andersen25f27032001-04-26 23:22:31 +00004392#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004393 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004394}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004395
4396
4397#if ENABLE_LASH
4398int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4399int lash_main(int argc, char **argv)
4400{
4401 //bb_error_msg("lash is deprecated, please use hush instead");
4402 return hush_main(argc, argv);
4403}
4404#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004405
4406
4407/*
4408 * Built-ins
4409 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004410static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004411{
4412 return 0;
4413}
4414
4415static int builtin_test(char **argv)
4416{
4417 int argc = 0;
4418 while (*argv) {
4419 argc++;
4420 argv++;
4421 }
4422 return test_main(argc, argv - argc);
4423}
4424
4425static int builtin_echo(char **argv)
4426{
4427 int argc = 0;
4428 while (*argv) {
4429 argc++;
4430 argv++;
4431 }
4432 return echo_main(argc, argv - argc);
4433}
4434
4435static int builtin_eval(char **argv)
4436{
4437 int rcode = EXIT_SUCCESS;
4438
4439 if (argv[1]) {
4440 char *str = expand_strvec_to_string(argv + 1);
4441 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4442 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004443 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004444 }
4445 return rcode;
4446}
4447
4448static int builtin_cd(char **argv)
4449{
4450 const char *newdir;
4451 if (argv[1] == NULL) {
4452 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4453 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4454 newdir = getenv("HOME") ? : "/";
4455 } else
4456 newdir = argv[1];
4457 if (chdir(newdir)) {
4458 printf("cd: %s: %s\n", newdir, strerror(errno));
4459 return EXIT_FAILURE;
4460 }
4461 set_cwd();
4462 return EXIT_SUCCESS;
4463}
4464
4465static int builtin_exec(char **argv)
4466{
4467 if (argv[1] == NULL)
4468 return EXIT_SUCCESS; /* bash does this */
4469 {
4470#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004471 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004472#endif
4473// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004474 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004475 /* never returns */
4476 }
4477}
4478
4479static int builtin_exit(char **argv)
4480{
4481// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4482 //puts("exit"); /* bash does it */
4483// TODO: warn if we have background jobs: "There are stopped jobs"
4484// On second consecutive 'exit', exit anyway.
4485 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004486 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004487 /* mimic bash: exit 123abc == exit 255 + error msg */
4488 xfunc_error_retval = 255;
4489 /* bash: exit -2 == exit 254, no error msg */
4490 hush_exit(xatoi(argv[1]) & 0xff);
4491}
4492
4493static int builtin_export(char **argv)
4494{
4495 const char *value;
4496 char *name = argv[1];
4497
4498 if (name == NULL) {
4499 // TODO:
4500 // ash emits: export VAR='VAL'
4501 // bash: declare -x VAR="VAL"
4502 // (both also escape as needed (quotes, $, etc))
4503 char **e = environ;
4504 if (e)
4505 while (*e)
4506 puts(*e++);
4507 return EXIT_SUCCESS;
4508 }
4509
4510 value = strchr(name, '=');
4511 if (!value) {
4512 /* They are exporting something without a =VALUE */
4513 struct variable *var;
4514
4515 var = get_local_var(name);
4516 if (var) {
4517 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004518 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004519 putenv(var->varstr);
4520 }
4521 /* bash does not return an error when trying to export
4522 * an undefined variable. Do likewise. */
4523 return EXIT_SUCCESS;
4524 }
4525
4526 set_local_var(xstrdup(name), 1);
4527 return EXIT_SUCCESS;
4528}
4529
4530#if ENABLE_HUSH_JOB
4531/* built-in 'fg' and 'bg' handler */
4532static int builtin_fg_bg(char **argv)
4533{
4534 int i, jobnum;
4535 struct pipe *pi;
4536
Denis Vlasenko87a86552008-07-29 19:43:10 +00004537 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004538 return EXIT_FAILURE;
4539 /* If they gave us no args, assume they want the last backgrounded task */
4540 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004541 for (pi = G.job_list; pi; pi = pi->next) {
4542 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004543 goto found;
4544 }
4545 }
4546 bb_error_msg("%s: no current job", argv[0]);
4547 return EXIT_FAILURE;
4548 }
4549 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4550 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4551 return EXIT_FAILURE;
4552 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004553 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004554 if (pi->jobid == jobnum) {
4555 goto found;
4556 }
4557 }
4558 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4559 return EXIT_FAILURE;
4560 found:
4561 // TODO: bash prints a string representation
4562 // of job being foregrounded (like "sleep 1 | cat")
4563 if (*argv[0] == 'f') {
4564 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004565 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004566 }
4567
4568 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004569 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4570 for (i = 0; i < pi->num_cmds; i++) {
4571 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4572 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004573 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004574 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004575
4576 i = kill(- pi->pgrp, SIGCONT);
4577 if (i < 0) {
4578 if (errno == ESRCH) {
4579 delete_finished_bg_job(pi);
4580 return EXIT_SUCCESS;
4581 } else {
4582 bb_perror_msg("kill (SIGCONT)");
4583 }
4584 }
4585
4586 if (*argv[0] == 'f') {
4587 remove_bg_job(pi);
4588 return checkjobs_and_fg_shell(pi);
4589 }
4590 return EXIT_SUCCESS;
4591}
4592#endif
4593
4594#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004595static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004596{
4597 const struct built_in_command *x;
4598
4599 printf("\nBuilt-in commands:\n");
4600 printf("-------------------\n");
4601 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4602 printf("%s\t%s\n", x->cmd, x->descr);
4603 }
4604 printf("\n\n");
4605 return EXIT_SUCCESS;
4606}
4607#endif
4608
4609#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004610static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004611{
4612 struct pipe *job;
4613 const char *status_string;
4614
Denis Vlasenko87a86552008-07-29 19:43:10 +00004615 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004616 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004617 status_string = "Stopped";
4618 else
4619 status_string = "Running";
4620
4621 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4622 }
4623 return EXIT_SUCCESS;
4624}
4625#endif
4626
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004627static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004628{
4629 puts(set_cwd());
4630 return EXIT_SUCCESS;
4631}
4632
4633static int builtin_read(char **argv)
4634{
4635 char *string;
4636 const char *name = argv[1] ? argv[1] : "REPLY";
4637
4638 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4639 return set_local_var(string, 0);
4640}
4641
4642/* built-in 'set [VAR=value]' handler */
4643static int builtin_set(char **argv)
4644{
4645 char *temp = argv[1];
4646 struct variable *e;
4647
4648 if (temp == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004649 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004650 puts(e->varstr);
4651 else
4652 set_local_var(xstrdup(temp), 0);
4653
4654 return EXIT_SUCCESS;
4655}
4656
4657static int builtin_shift(char **argv)
4658{
4659 int n = 1;
4660 if (argv[1]) {
4661 n = atoi(argv[1]);
4662 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004663 if (n >= 0 && n < G.global_argc) {
4664 G.global_argv[n] = G.global_argv[0];
4665 G.global_argc -= n;
4666 G.global_argv += n;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004667 return EXIT_SUCCESS;
4668 }
4669 return EXIT_FAILURE;
4670}
4671
4672static int builtin_source(char **argv)
4673{
4674 FILE *input;
4675 int status;
4676
4677 if (argv[1] == NULL)
4678 return EXIT_FAILURE;
4679
4680 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004681 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004682 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004683 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004684 return EXIT_FAILURE;
4685 }
4686 close_on_exec_on(fileno(input));
4687
4688 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004689 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004690 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00004691 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004692 status = parse_and_run_file(input);
4693 fclose(input);
4694 return status;
4695}
4696
4697static int builtin_umask(char **argv)
4698{
4699 mode_t new_umask;
4700 const char *arg = argv[1];
4701 char *end;
4702 if (arg) {
4703 new_umask = strtoul(arg, &end, 8);
4704 if (*end != '\0' || end == arg) {
4705 return EXIT_FAILURE;
4706 }
4707 } else {
4708 new_umask = umask(0);
4709 printf("%.3o\n", (unsigned) new_umask);
4710 }
4711 umask(new_umask);
4712 return EXIT_SUCCESS;
4713}
4714
4715static int builtin_unset(char **argv)
4716{
4717 /* bash always returns true */
4718 unset_local_var(argv[1]);
4719 return EXIT_SUCCESS;
4720}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004721
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004722#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004723static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004724{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004725 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004726 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004727 return EXIT_SUCCESS; /* bash compat */
4728 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004729 G.flag_break_continue++; /* BC_BREAK = 1 */
4730 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004731 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004732 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4733 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004734 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004735 G.flag_break_continue = BC_BREAK;
4736 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004737 }
4738 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004739 if (G.depth_of_loop < G.depth_break_continue)
4740 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004741 return EXIT_SUCCESS;
4742}
4743
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004744static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004745{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004746 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4747 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004748}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004749#endif