blob: 7cf2f3322fba5f2c5a305aa6b7f1c066d82447cd [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 Vlasenkod01ff132007-05-02 21:40:23 +000099/* If you comment out one of these below, it will be #defined later
100 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000101#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000102/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000103#define debug_printf_parse(...) do {} while (0)
104#define debug_print_tree(a, b) do {} while (0)
105#define debug_printf_exec(...) do {} while (0)
106#define debug_printf_jobs(...) do {} while (0)
107#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000108#define debug_printf_glob(...) do {} while (0)
109#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000110#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000111#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000112
113#ifndef debug_printf
114#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000115#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000116
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000117#ifndef debug_printf_parse
118#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000119#endif
120
121#ifndef debug_printf_exec
122#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
123#endif
124
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000125#ifndef debug_printf_jobs
126#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000127#define DEBUG_JOBS 1
128#else
129#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000130#endif
131
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000132#ifndef debug_printf_expand
133#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
134#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000135#else
136#define DEBUG_EXPAND 0
137#endif
138
139#ifndef debug_printf_glob
140#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
141#define DEBUG_GLOB 1
142#else
143#define DEBUG_GLOB 0
144#endif
145
146#ifndef debug_printf_list
147#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000148#endif
149
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000150#ifndef debug_printf_subst
151#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
152#endif
153
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000154#ifndef debug_printf_clean
155/* broken, of course, but OK for testing */
156static const char *indenter(int i)
157{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000158 static const char blanks[] ALIGN1 =
159 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000160 return &blanks[sizeof(blanks) - i - 1];
161}
162#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000163#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000164#endif
165
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000166#if DEBUG_EXPAND
167static void debug_print_strings(const char *prefix, char **vv)
168{
169 fprintf(stderr, "%s:\n", prefix);
170 while (*vv)
171 fprintf(stderr, " '%s'\n", *vv++);
172}
173#else
174#define debug_print_strings(prefix, vv) ((void)0)
175#endif
176
Denis Vlasenkof962a032007-11-23 12:50:54 +0000177/*
178 * Leak hunting. Use hush_leaktool.sh for post-processing.
179 */
180#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000181/* suppress "warning: no previous prototype..." */
182void *xxmalloc(int lineno, size_t size);
183void *xxrealloc(int lineno, void *ptr, size_t size);
184char *xxstrdup(int lineno, const char *str);
185void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000186void *xxmalloc(int lineno, size_t size)
187{
188 void *ptr = xmalloc((size + 0xff) & ~0xff);
189 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
190 return ptr;
191}
192void *xxrealloc(int lineno, void *ptr, size_t size)
193{
194 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
195 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
196 return ptr;
197}
198char *xxstrdup(int lineno, const char *str)
199{
200 char *ptr = xstrdup(str);
201 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
202 return ptr;
203}
204void xxfree(void *ptr)
205{
206 fprintf(stderr, "free %p\n", ptr);
207 free(ptr);
208}
209#define xmalloc(s) xxmalloc(__LINE__, s)
210#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
211#define xstrdup(s) xxstrdup(__LINE__, s)
212#define free(p) xxfree(p)
213#endif
214
215
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000216/* Keep unconditionally on for now */
217#define HUSH_DEBUG 1
218/* Do we support ANY keywords? */
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000219#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000220#define HAS_KEYWORDS 1
221#define IF_HAS_KEYWORDS(...) __VA_ARGS__
222#define IF_HAS_NO_KEYWORDS(...)
223#else
224#define HAS_KEYWORDS 0
225#define IF_HAS_KEYWORDS(...)
226#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
227#endif
228
229
Denis Vlasenko5703c222008-06-15 11:49:42 +0000230#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000231#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000232
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000233typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000234 REDIRECT_INPUT = 1,
235 REDIRECT_OVERWRITE = 2,
236 REDIRECT_APPEND = 3,
237 REDIRECT_HEREIS = 4,
238 REDIRECT_IO = 5
239} redir_type;
240
Denis Vlasenko55789c62008-06-18 16:30:42 +0000241/* The descrip member of this structure is only used to make
242 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000243static const struct {
244 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000245 signed char default_fd;
246 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000247} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000248 { 0, 0, "()" },
249 { O_RDONLY, 0, "<" },
250 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
251 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
252 { O_RDONLY, -1, "<<" },
253 { O_RDWR, 1, "<>" }
254};
255
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000256typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000257 PIPE_SEQ = 1,
258 PIPE_AND = 2,
259 PIPE_OR = 3,
260 PIPE_BG = 4,
261} pipe_style;
262
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000263typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000264 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000265#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000266 RES_IF ,
267 RES_THEN ,
268 RES_ELIF ,
269 RES_ELSE ,
270 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000271#endif
272#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000273 RES_FOR ,
274 RES_WHILE ,
275 RES_UNTIL ,
276 RES_DO ,
277 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000278#endif
279#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000280 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000281#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000282#if ENABLE_HUSH_CASE
283 RES_CASE ,
284 /* two pseudo-keywords support contrived "case" syntax: */
285 RES_MATCH , /* "word)" */
286 RES_CASEI , /* "this command is inside CASE" */
287 RES_ESAC ,
288#endif
289 RES_XXXX ,
290 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000291} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000292
Eric Andersen25f27032001-04-26 23:22:31 +0000293struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000294 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000295 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000296 int fd; /* file descriptor being redirected */
297 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000298 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000299};
300
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000301struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000302 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000303 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000304 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000305 smallint subshell; /* flag, non-zero if group must be forked */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000306 struct pipe *group; /* if non-NULL, this "prog" is {} group,
307 * subshell, or a compound statement */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000308 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000309 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000310};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000311/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
312 * and on execution these are substituted with their values.
313 * Substitution can make _several_ words out of one argv[n]!
314 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000315 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000316 */
Eric Andersen25f27032001-04-26 23:22:31 +0000317
318struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000319 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000320 int num_cmds; /* total number of commands in job */
321 int alive_cmds; /* number of commands running (not exited) */
322 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000323#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000324 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000325 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000326 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000327#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000328 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000329 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000330 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
331 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000332};
333
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000334/* This holds pointers to the various results of parsing */
335struct parse_context {
336 struct command *command;
337 struct pipe *list_head;
338 struct pipe *pipe;
339 struct redir_struct *pending_redirect;
340#if HAS_KEYWORDS
341 smallint ctx_res_w;
342 smallint ctx_inverted; /* "! cmd | cmd" */
343#if ENABLE_HUSH_CASE
344 smallint ctx_dsemicolon; /* ";;" seen */
345#endif
346 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
347 struct parse_context *stack;
348#endif
349};
350
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000351/* On program start, environ points to initial environment.
352 * putenv adds new pointers into it, unsetenv removes them.
353 * Neither of these (de)allocates the strings.
354 * setenv allocates new strings in malloc space and does putenv,
355 * and thus setenv is unusable (leaky) for shell's purposes */
356#define setenv(...) setenv_is_leaky_dont_use()
357struct variable {
358 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000359 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000360 int max_len; /* if > 0, name is part of initial env; else name is malloced */
361 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000362 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000363};
364
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000365typedef struct o_string {
Eric Andersen25f27032001-04-26 23:22:31 +0000366 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000367 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000368 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000369 /* Misnomer! it's not "quoting", it's "protection against globbing"!
370 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000371 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000372 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000373 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000374 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000375 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000376} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000377enum {
378 MAYBE_ASSIGNMENT = 0,
379 DEFINITELY_ASSIGNMENT = 1,
380 NOT_ASSIGNMENT = 2,
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000381 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000382};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000383/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000384#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000385
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000386/* I can almost use ordinary FILE*. Is open_memstream() universally
Eric Andersen25f27032001-04-26 23:22:31 +0000387 * available? Where is it documented? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000388typedef struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000389 const char *p;
390 /* eof_flag=1: last char in ->p is really an EOF */
391 char eof_flag; /* meaningless if ->p == NULL */
392 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000393#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000394 smallint promptme;
395 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000396#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000397 FILE *file;
398 int (*get) (struct in_str *);
399 int (*peek) (struct in_str *);
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000400} in_str;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000401#define i_getch(input) ((input)->get(input))
402#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000403
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000404enum {
405 CHAR_ORDINARY = 0,
406 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
407 CHAR_IFS = 2, /* treated as ordinary if quoted */
408 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000409};
410
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000411enum {
412 BC_BREAK = 1,
413 BC_CONTINUE = 2,
414};
415
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000416
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000417/* "Globals" within this file */
418
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000419/* Sorted roughly by size (smaller offsets == smaller code) */
420struct globals {
421#if ENABLE_HUSH_INTERACTIVE
422 /* 'interactive_fd' is a fd# open to ctty, if we have one
423 * _AND_ if we decided to act interactively */
424 int interactive_fd;
425 const char *PS1;
426 const char *PS2;
427#endif
428#if ENABLE_FEATURE_EDITING
429 line_input_t *line_input_state;
430#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000431 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000432 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000433#if ENABLE_HUSH_JOB
434 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000435 pid_t saved_tty_pgrp;
436 int last_jobid;
437 struct pipe *job_list;
438 struct pipe *toplevel_list;
439 smallint ctrl_z_flag;
440#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000441#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000442 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000443#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000444 smallint fake_mode;
445 /* these three support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000446 smalluint last_return_code;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000447 char **global_argv;
448 int global_argc;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000449#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000450 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000451 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000452#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000453 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000454 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000455 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000456 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000457#if ENABLE_FEATURE_SH_STANDALONE
458 struct nofork_save_area nofork_save;
459#endif
460#if ENABLE_HUSH_JOB
461 sigjmp_buf toplevel_jb;
462#endif
463 unsigned char charmap[256];
464 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
465};
466
467#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000468/* Not #defining name to G.name - this quickly gets unwieldy
469 * (too many defines). Also, I actually prefer to see when a variable
470 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000471#define INIT_G() do { \
472 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
473} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000474
475
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000476#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
477
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000478#if 1
479/* Normal */
480static void syntax(const char *msg)
481{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000482#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000483 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000484 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000485 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000486 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000487 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000488 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000489#else
490 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
491#endif
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000492}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000493
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000494#else
495/* Debug */
496static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000497{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000498#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoff182a32008-07-05 20:29:59 +0000499 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000500 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000501 fp("syntax error hush.c:%d", line);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000502#else
503 bb_error_msg_and_die("syntax error hush.c:%d", line);
504#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000505}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000506#define syntax(str) syntax_lineno(__LINE__)
507#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000508
509/* Index of subroutines: */
Eric Andersen25f27032001-04-26 23:22:31 +0000510/* in_str manipulations: */
511static int static_get(struct in_str *i);
512static int static_peek(struct in_str *i);
513static int file_get(struct in_str *i);
514static int file_peek(struct in_str *i);
515static void setup_file_in_str(struct in_str *i, FILE *f);
516static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000517/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000518#if !defined(DEBUG_CLEAN)
519#define free_pipe_list(head, indent) free_pipe_list(head)
520#define free_pipe(pi, indent) free_pipe(pi)
521#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000522static int free_pipe_list(struct pipe *head, int indent);
523static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000524/* really run the final data structures: */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000525static int setup_redirects(struct command *prog, int squirrel[]);
Denis Vlasenko05743d72008-02-10 12:10:08 +0000526static int run_list(struct pipe *pi);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000527#if BB_MMU
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000528#define pseudo_exec_argv(ptr_ptrs2free, argv, assignment_cnt, argv_expanded) \
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000529 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000530#define pseudo_exec(ptr_ptrs2free, command, argv_expanded) \
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000531 pseudo_exec(command, argv_expanded)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000532#endif
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000533static void pseudo_exec_argv(char ***ptr_ptrs2free, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
534static void pseudo_exec(char ***ptr_ptrs2free, struct command *command, char **argv_expanded) NORETURN;
Denis Vlasenko05743d72008-02-10 12:10:08 +0000535static int run_pipe(struct pipe *pi);
Eric Andersen25f27032001-04-26 23:22:31 +0000536/* data structure manipulation: */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000537static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
538static void initialize_context(struct parse_context *ctx);
539static int done_word(o_string *dest, struct parse_context *ctx);
540static int done_command(struct parse_context *ctx);
541static void done_pipe(struct parse_context *ctx, pipe_style type);
Eric Andersen25f27032001-04-26 23:22:31 +0000542/* primary string parsing: */
543static int redirect_dup_num(struct in_str *input);
544static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000545#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000546static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000547 struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000548#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000549static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000550static const char *lookup_param(const char *src);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000551static int handle_dollar(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000552 struct in_str *input);
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000553static 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 +0000554/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000555static int parse_and_run_stream(struct in_str *inp, int parse_flag);
556static int parse_and_run_string(const char *s, int parse_flag);
557static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000558/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000559static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000560#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000561static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000562static void insert_bg_job(struct pipe *pi);
563static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000564static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000565#else
566int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
567#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000568/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000569static char **expand_strvec_to_strvec(char **argv);
570/* used for eval */
571static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000572/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000573static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000574static struct variable *get_local_var(const char *name);
575static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000576static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000577
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000578
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000579static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
580
581
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000582static int glob_needed(const char *s)
583{
584 while (*s) {
585 if (*s == '\\')
586 s++;
587 if (*s == '*' || *s == '[' || *s == '?')
588 return 1;
589 s++;
590 }
591 return 0;
592}
593
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000594static int is_assignment(const char *s)
595{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000596 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000597 return 0;
598 s++;
599 while (isalnum(*s) || *s == '_')
600 s++;
601 return *s == '=';
602}
603
Denis Vlasenko55789c62008-06-18 16:30:42 +0000604/* Replace each \x with x in place, return ptr past NUL. */
605static char *unbackslash(char *src)
606{
607 char *dst = src;
608 while (1) {
609 if (*src == '\\')
610 src++;
611 if ((*dst++ = *src++) == '\0')
612 break;
613 }
614 return dst;
615}
616
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000617static char **add_malloced_strings_to_strings(char **strings, char **add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000618{
619 int i;
620 unsigned count1;
621 unsigned count2;
622 char **v;
623
624 v = strings;
625 count1 = 0;
626 if (v) {
627 while (*v) {
628 count1++;
629 v++;
630 }
631 }
632 count2 = 0;
633 v = add;
634 while (*v) {
635 count2++;
636 v++;
637 }
638 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
639 v[count1 + count2] = NULL;
640 i = count2;
641 while (--i >= 0)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000642 v[count1 + i] = add[i];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000643 return v;
644}
645
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000646static char **add_malloced_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000647{
648 char *v[2];
649
650 v[0] = add;
651 v[1] = NULL;
652
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000653 return add_malloced_strings_to_strings(strings, v);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000654}
655
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000656static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000657{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000658 char **v;
659
660 if (!strings)
661 return;
662
663 v = strings;
664 while (*v) {
665 if (unset) {
666 char *copy;
667#if !BB_MMU
668 /* If this is a magic guard pointer, do not free it,
669 * and stop unsetting */
670 if (*v == hush_version_str) {
671 unset = 0;
672 v++;
673 continue;
674 }
675#endif
676 /* *strchrnul(*v, '=') = '\0'; -- BAD
677 * In case *v was putenv'ed, we can't
678 * unsetenv(*v) after taking out '=':
679 * it won't work, env is modified by taking out!
680 * horror :( */
681 copy = xstrndup(*v, strchrnul(*v, '=') - *v);
682 unsetenv(copy);
683 free(copy);
684 }
685 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000686 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000687 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000688}
689
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000690static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000691{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000692 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000693}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000694
695
Denis Vlasenko83506862007-11-23 13:11:42 +0000696/* Function prototypes for builtins */
697static int builtin_cd(char **argv);
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000698static int builtin_echo(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000699static int builtin_eval(char **argv);
700static int builtin_exec(char **argv);
701static int builtin_exit(char **argv);
702static int builtin_export(char **argv);
703#if ENABLE_HUSH_JOB
704static int builtin_fg_bg(char **argv);
705static int builtin_jobs(char **argv);
706#endif
707#if ENABLE_HUSH_HELP
708static int builtin_help(char **argv);
709#endif
710static int builtin_pwd(char **argv);
711static int builtin_read(char **argv);
712static int builtin_test(char **argv);
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000713static int builtin_true(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000714static int builtin_set(char **argv);
715static int builtin_shift(char **argv);
716static int builtin_source(char **argv);
717static int builtin_umask(char **argv);
718static int builtin_unset(char **argv);
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000719#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000720static int builtin_break(char **argv);
721static int builtin_continue(char **argv);
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000722#endif
Denis Vlasenko83506862007-11-23 13:11:42 +0000723//static int builtin_not_written(char **argv);
724
Eric Andersen25f27032001-04-26 23:22:31 +0000725/* Table of built-in functions. They can be forked or not, depending on
726 * context: within pipes, they fork. As simple commands, they do not.
727 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000728 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000729 * For example, 'unset foo | whatever' will parse and run, but foo will
730 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000731struct built_in_command {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000732 const char *cmd;
733 int (*function)(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000734#if ENABLE_HUSH_HELP
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000735 const char *descr;
Denis Vlasenko06810332007-05-21 23:30:54 +0000736#define BLTIN(cmd, func, help) { cmd, func, help }
737#else
738#define BLTIN(cmd, func, help) { cmd, func }
739#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000740};
741
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000742/* For now, echo and test are unconditionally enabled.
743 * Maybe make it configurable? */
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000744static const struct built_in_command bltins[] = {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000745 BLTIN("." , builtin_source, "Run commands in a file"),
746 BLTIN(":" , builtin_true, "No-op"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000747 BLTIN("[" , builtin_test, "Test condition"),
748 BLTIN("[[" , builtin_test, "Test condition"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000749#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000750 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000751#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000752#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000753 BLTIN("break" , builtin_break, "Exit from a loop"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000754#endif
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000755 BLTIN("cd" , builtin_cd, "Change directory"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000756#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000757 BLTIN("continue", builtin_continue, "Start new loop iteration"),
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000758#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000759 BLTIN("echo" , builtin_echo, "Write to stdout"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000760 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000761 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
762 BLTIN("exit" , builtin_exit, "Exit"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000763 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000764#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000765 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000766 BLTIN("jobs" , builtin_jobs, "List active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000767#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000768 BLTIN("pwd" , builtin_pwd, "Print current directory"),
769 BLTIN("read" , builtin_read, "Input environment variable"),
770// BLTIN("return", builtin_not_written, "Return from a function"),
771 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
772 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
773// BLTIN("trap" , builtin_not_written, "Trap signals"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000774 BLTIN("test" , builtin_test, "Test condition"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000775// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
776 BLTIN("umask" , builtin_umask, "Set file creation mask"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000777 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000778#if ENABLE_HUSH_HELP
779 BLTIN("help" , builtin_help, "List shell built-in commands"),
780#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000781};
782
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000783
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000784/* Signals are grouped, we handle them in batches */
785static void set_misc_sighandler(void (*handler)(int))
786{
787 bb_signals(0
788 + (1 << SIGINT)
789 + (1 << SIGQUIT)
790 + (1 << SIGTERM)
791 , handler);
792}
793
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000794#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000795
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000796static void set_fatal_sighandler(void (*handler)(int))
797{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000798 bb_signals(0
799 + (1 << SIGILL)
800 + (1 << SIGTRAP)
801 + (1 << SIGABRT)
802 + (1 << SIGFPE)
803 + (1 << SIGBUS)
804 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000805 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000806 + (1 << SIGHUP)
807 + (1 << SIGPIPE)
808 + (1 << SIGALRM)
809 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000810}
811static void set_jobctrl_sighandler(void (*handler)(int))
812{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000813 bb_signals(0
814 + (1 << SIGTSTP)
815 + (1 << SIGTTIN)
816 + (1 << SIGTTOU)
817 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000818}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000819/* SIGCHLD is special and handled separately */
820
821static void set_every_sighandler(void (*handler)(int))
822{
823 set_fatal_sighandler(handler);
824 set_jobctrl_sighandler(handler);
825 set_misc_sighandler(handler);
826 signal(SIGCHLD, handler);
827}
828
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000829static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000830{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000831 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000832// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000833 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000834}
835
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000836static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000837{
838 pid_t pid;
839
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000840 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000841 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000842 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000843 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000844 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000845 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000846 if (ENABLE_HUSH_JOB)
847 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000848 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000849 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000850 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000851 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000852 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000853 /* return to nofork, it will eventually exit now,
854 * not return back to shell */
855 return;
856 }
857 /* parent */
858 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000859 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000860 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000861 /* parent needs to longjmp out of running nofork.
862 * we will "return" exitcode 0, with child put in background */
863// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000864 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000865 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000866}
867
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000868/* Restores tty foreground process group, and exits.
869 * May be called as signal handler for fatal signal
870 * (will faithfully resend signal to itself, producing correct exit state)
871 * or called directly with -EXITCODE.
872 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000873static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000874static void sigexit(int sig)
875{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000876 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000877 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000878
Denis Vlasenko87a86552008-07-29 19:43:10 +0000879#if ENABLE_HUSH_INTERACTIVE
880 if (G.interactive_fd)
881 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
882#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000883
884 /* Not a signal, just exit */
885 if (sig <= 0)
886 _exit(- sig);
887
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000888 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000889}
890
891/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000892static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000893static void hush_exit(int exitcode)
894{
895 fflush(NULL); /* flush all streams */
896 sigexit(- (exitcode & 0xff));
897}
898
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000899#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000900
901#define set_fatal_sighandler(handler) ((void)0)
902#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000903#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000904
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000905#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000906
907
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000908static const char *set_cwd(void)
909{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000910 if (G.cwd == bb_msg_unknown)
911 G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
912 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
913 if (!G.cwd)
914 G.cwd = bb_msg_unknown;
915 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000916}
917
Denis Vlasenko83506862007-11-23 13:11:42 +0000918
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000919/*
920 * o_string support
921 */
922#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +0000923
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000924static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000925{
926 o->length = 0;
927 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000928 if (o->data)
929 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000930}
931
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000932static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000933{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +0000934 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000935 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +0000936}
937
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000938static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000939{
940 if (o->length + len > o->maxlen) {
941 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
942 o->data = xrealloc(o->data, 1 + o->maxlen);
943 }
944}
945
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000946static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000947{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000948 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
949 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000950 o->data[o->length] = ch;
951 o->length++;
952 o->data[o->length] = '\0';
953}
954
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000955static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000956{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000957 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000958 memcpy(&o->data[o->length], str, len);
959 o->length += len;
960 o->data[o->length] = '\0';
961}
962
Denis Vlasenko55789c62008-06-18 16:30:42 +0000963static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
964{
965 while (len) {
966 o_addchr(o, *str);
967 if (*str++ == '\\'
968 && (*str != '*' && *str != '?' && *str != '[')
969 ) {
970 o_addchr(o, '\\');
971 }
972 len--;
973 }
974}
975
Eric Andersen25f27032001-04-26 23:22:31 +0000976/* My analysis of quoting semantics tells me that state information
977 * is associated with a destination, not a source.
978 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000979static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +0000980{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000981 int sz = 1;
982 if (strchr("*?[\\", ch)) {
983 sz++;
984 o->data[o->length] = '\\';
985 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +0000986 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000987 o_grow_by(o, sz);
988 o->data[o->length] = ch;
989 o->length++;
990 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000991}
992
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000993static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000994{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000995 int sz = 1;
996 if (o->o_quote && strchr("*?[\\", ch)) {
997 sz++;
998 o->data[o->length] = '\\';
999 o->length++;
1000 }
1001 o_grow_by(o, sz);
1002 o->data[o->length] = ch;
1003 o->length++;
1004 o->data[o->length] = '\0';
1005}
1006
1007static void o_addQstr(o_string *o, const char *str, int len)
1008{
1009 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001010 o_addstr(o, str, len);
1011 return;
1012 }
1013 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001014 char ch;
1015 int sz;
1016 int ordinary_cnt = strcspn(str, "*?[\\");
1017 if (ordinary_cnt > len) /* paranoia */
1018 ordinary_cnt = len;
1019 o_addstr(o, str, ordinary_cnt);
1020 if (ordinary_cnt == len)
1021 return;
1022 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001023 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001024
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001025 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001026 sz = 1;
1027 if (ch) { /* it is necessarily one of "*?[\\" */
1028 sz++;
1029 o->data[o->length] = '\\';
1030 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001031 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001032 o_grow_by(o, sz);
1033 o->data[o->length] = ch;
1034 o->length++;
1035 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001036 }
1037}
1038
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001039/* A special kind of o_string for $VAR and `cmd` expansion.
1040 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001041 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001042 * list[i] contains an INDEX (int!) into this string data.
1043 * It means that if list[] needs to grow, data needs to be moved higher up
1044 * but list[i]'s need not be modified.
1045 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001046 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001047 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1048 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001049#if DEBUG_EXPAND || DEBUG_GLOB
1050static void debug_print_list(const char *prefix, o_string *o, int n)
1051{
1052 char **list = (char**)o->data;
1053 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1054 int i = 0;
1055 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1056 prefix, list, n, string_start, o->length, o->maxlen);
1057 while (i < n) {
1058 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1059 o->data + (int)list[i] + string_start,
1060 o->data + (int)list[i] + string_start);
1061 i++;
1062 }
1063 if (n) {
1064 const char *p = o->data + (int)list[n - 1] + string_start;
1065 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1066 }
1067}
1068#else
1069#define debug_print_list(prefix, o, n) ((void)0)
1070#endif
1071
1072/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1073 * in list[n] so that it points past last stored byte so far.
1074 * It returns n+1. */
1075static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001076{
1077 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001078 int string_start;
1079 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001080
1081 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001082 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1083 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001084 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001085 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001086 /* list[n] points to string_start, make space for 16 more pointers */
1087 o->maxlen += 0x10 * sizeof(list[0]);
1088 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001089 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001090 memmove(list + n + 0x10, list + n, string_len);
1091 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001092 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001093 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001094 } else {
1095 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001096 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1097 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001098 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001099 o->has_empty_slot = 0;
1100 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001101 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001102 return n + 1;
1103}
1104
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001105/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001106static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001107{
1108 char **list = (char**)o->data;
1109 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1110
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001111 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001112}
1113
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001114/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001115 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001116static int o_glob(o_string *o, int n)
1117{
1118 glob_t globdata;
1119 int gr;
1120 char *pattern;
1121
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001122 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001123 if (!o->data)
1124 return o_save_ptr_helper(o, n);
1125 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001126 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001127 if (!glob_needed(pattern)) {
1128 literal:
1129 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001130 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001131 return o_save_ptr_helper(o, n);
1132 }
1133
1134 memset(&globdata, 0, sizeof(globdata));
1135 gr = glob(pattern, 0, NULL, &globdata);
1136 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1137 if (gr == GLOB_NOSPACE)
1138 bb_error_msg_and_die("out of memory during glob");
1139 if (gr == GLOB_NOMATCH) {
1140 globfree(&globdata);
1141 goto literal;
1142 }
1143 if (gr != 0) { /* GLOB_ABORTED ? */
1144//TODO: testcase for bad glob pattern behavior
1145 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1146 }
1147 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1148 char **argv = globdata.gl_pathv;
1149 o->length = pattern - o->data; /* "forget" pattern */
1150 while (1) {
1151 o_addstr(o, *argv, strlen(*argv) + 1);
1152 n = o_save_ptr_helper(o, n);
1153 argv++;
1154 if (!*argv)
1155 break;
1156 }
1157 }
1158 globfree(&globdata);
1159 if (DEBUG_GLOB)
1160 debug_print_list("o_glob returning", o, n);
1161 return n;
1162}
1163
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001164/* If o->o_glob == 1, glob the string so far remembered.
1165 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001166static int o_save_ptr(o_string *o, int n)
1167{
1168 if (o->o_glob)
1169 return o_glob(o, n); /* o_save_ptr_helper is inside */
1170 return o_save_ptr_helper(o, n);
1171}
1172
1173/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001174static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001175{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001176 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001177 int string_start;
1178
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001179 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1180 if (DEBUG_EXPAND)
1181 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001182 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001183 list = (char**)o->data;
1184 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1185 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001186 while (n) {
1187 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001188 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001189 }
1190 return list;
1191}
1192
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001193
1194/*
1195 * in_str support
1196 */
Eric Andersen25f27032001-04-26 23:22:31 +00001197static int static_get(struct in_str *i)
1198{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001199 int ch = *i->p++;
1200 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001201 return ch;
1202}
1203
1204static int static_peek(struct in_str *i)
1205{
1206 return *i->p;
1207}
1208
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001209#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001210
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001211#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001212static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001213{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001214#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denis Vlasenko87a86552008-07-29 19:43:10 +00001215 G.PS1 = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00001216#else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001217 G.PS1 = getenv("PS1");
1218 if (G.PS1 == NULL)
1219 G.PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001220#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001221}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001222#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001223
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001224static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001225{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001226 const char *prompt_str;
1227 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001228#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001229 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001230 if (promptmode == 0) { /* PS1 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001231 free((char*)G.PS1);
1232 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1233 prompt_str = G.PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001234 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001235 prompt_str = G.PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001236 }
1237#else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001238 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001239#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001240 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001241 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001242}
1243
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001244static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001245{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001246 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001247 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001248
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001249 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001250#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001251 /* Enable command line editing only while a command line
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001252 * is actually being read */
1253 do {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001254 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001255 } while (r == 0); /* repeat if Ctrl-C */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001256 i->eof_flag = (r < 0);
1257 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001258 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1259 G.user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001260 }
Eric Andersen25f27032001-04-26 23:22:31 +00001261#else
1262 fputs(prompt_str, stdout);
1263 fflush(stdout);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001264 G.user_input_buf[0] = r = fgetc(i->file);
1265 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001266 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001267#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00001268 i->p = G.user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001269}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001270
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001271#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001272
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001273/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001274 * and gets data back from the user */
1275static int file_get(struct in_str *i)
1276{
1277 int ch;
1278
Eric Andersen25f27032001-04-26 23:22:31 +00001279 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001280 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001281#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001282 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001283#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001284 ch = *i->p++;
1285 if (i->eof_flag && !*i->p)
1286 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001287 } else {
1288 /* need to double check i->file because we might be doing something
1289 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001290#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko87a86552008-07-29 19:43:10 +00001291 if (G.interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001292 do {
1293 get_user_input(i);
1294 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001295 i->promptmode = 1; /* PS2 */
1296 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001297 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001298 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001299#endif
1300 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001301 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001302 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001303#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001304 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001305 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001306#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001307 return ch;
1308}
1309
1310/* All the callers guarantee this routine will never be
1311 * used right after a newline, so prompting is not needed.
1312 */
1313static int file_peek(struct in_str *i)
1314{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001315 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001316 if (i->p && *i->p) {
1317 if (i->eof_flag && !i->p[1])
1318 return EOF;
1319 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001320 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001321 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001322 i->eof_flag = (ch == EOF);
1323 i->peek_buf[0] = ch;
1324 i->peek_buf[1] = '\0';
1325 i->p = i->peek_buf;
1326 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001327 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001328}
1329
1330static void setup_file_in_str(struct in_str *i, FILE *f)
1331{
1332 i->peek = file_peek;
1333 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001334#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001335 i->promptme = 1;
1336 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001337#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001338 i->file = f;
1339 i->p = NULL;
1340}
1341
1342static void setup_string_in_str(struct in_str *i, const char *s)
1343{
1344 i->peek = static_peek;
1345 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001346#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001347 i->promptme = 1;
1348 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001349#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001350 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001351 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001352}
1353
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001354
Eric Andersen25f27032001-04-26 23:22:31 +00001355/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1356 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001357static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001358{
1359 int openfd, mode;
1360 struct redir_struct *redir;
1361
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001362 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001363 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001364 /* something went wrong in the parse. Pretend it didn't happen */
1365 continue;
1366 }
Eric Andersen25f27032001-04-26 23:22:31 +00001367 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001368 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001369 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001370//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001371 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001372 openfd = open_or_warn(p, mode);
1373 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001374 if (openfd < 0) {
1375 /* this could get lost if stderr has been redirected, but
1376 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001377 return 1;
1378 }
1379 } else {
1380 openfd = redir->dup;
1381 }
1382
1383 if (openfd != redir->fd) {
1384 if (squirrel && redir->fd < 3) {
1385 squirrel[redir->fd] = dup(redir->fd);
1386 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001387 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001388 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001389 } else {
1390 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001391 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001392 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001393 }
Eric Andersen25f27032001-04-26 23:22:31 +00001394 }
1395 }
1396 return 0;
1397}
1398
1399static void restore_redirects(int squirrel[])
1400{
1401 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001402 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001403 fd = squirrel[i];
1404 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001405 /* We simply die on error */
1406 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001407 }
1408 }
1409}
1410
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001411
Denis Vlasenko05743d72008-02-10 12:10:08 +00001412/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001413 * Never returns.
1414 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001415 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001416 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001417static void pseudo_exec_argv(char ***ptr_ptrs2free, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001418{
Eric Andersen78a7c992001-05-15 16:30:25 +00001419 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001420 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001421 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001422
Denis Vlasenko1359da62007-04-21 23:27:30 +00001423 /* If a variable is assigned in a forest, and nobody listens,
1424 * was it ever really set?
1425 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001426 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001427 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001428
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001429 for (i = 0; i < assignment_cnt; i++) {
1430 debug_printf_exec("pid %d environment modification: %s\n",
1431 getpid(), *argv);
1432 p = expand_string_to_string(*argv);
1433 putenv(p);
1434#if !BB_MMU
1435 *ptr_ptrs2free = add_malloced_string_to_strings(*ptr_ptrs2free, p);
1436#endif
1437 argv++;
1438 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001439 if (argv_expanded) {
1440 argv = argv_expanded;
1441 } else {
1442 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001443#if !BB_MMU
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001444 /* Inserting magic guard pointer to not unsetenv junk later */
1445 *ptr_ptrs2free = add_malloced_string_to_strings(*ptr_ptrs2free, (char*)hush_version_str);
1446 *ptr_ptrs2free = add_malloced_string_to_strings(*ptr_ptrs2free, (char*)argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001447#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001448 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001449
Denis Vlasenko1359da62007-04-21 23:27:30 +00001450 /*
1451 * Check if the command matches any of the builtins.
1452 * Depending on context, this might be redundant. But it's
1453 * easier to waste a few CPU cycles than it is to figure out
1454 * if this is one of those cases.
1455 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001456 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001457 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001458 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001459 rcode = x->function(argv);
1460 fflush(stdout);
1461 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001462 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001463 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001464
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001465 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001466#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001467 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001468 int a = find_applet_by_name(argv[0]);
1469 if (a >= 0) {
1470 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001471 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001472// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1473 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001474 }
1475 /* re-exec ourselves with the new arguments */
1476 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001477 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001478 /* If they called chroot or otherwise made the binary no longer
1479 * executable, fall through */
1480 }
1481 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001482#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001483
1484 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001485 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00001486 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001487 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001488}
1489
Denis Vlasenko05743d72008-02-10 12:10:08 +00001490/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001491 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001492static void pseudo_exec(char ***ptr_ptrs2free, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001493{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001494 if (command->argv)
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001495 pseudo_exec_argv(ptr_ptrs2free, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001496
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001497 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001498#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001499 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001500#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001501 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001502 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001503 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001504 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001505 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001506 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001507#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001508 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001509
1510 /* Can happen. See what bash does with ">foo" by itself. */
1511 debug_printf("trying to pseudo_exec null command\n");
1512 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001513}
1514
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001515#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001516static const char *get_cmdtext(struct pipe *pi)
1517{
1518 char **argv;
1519 char *p;
1520 int len;
1521
1522 /* This is subtle. ->cmdtext is created only on first backgrounding.
1523 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001524 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001525 if (pi->cmdtext)
1526 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001527 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001528 if (!argv || !argv[0]) {
1529 pi->cmdtext = xzalloc(1);
1530 return pi->cmdtext;
1531 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001532
1533 len = 0;
1534 do len += strlen(*argv) + 1; while (*++argv);
1535 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001536 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001537 do {
1538 len = strlen(*argv);
1539 memcpy(p, *argv, len);
1540 p += len;
1541 *p++ = ' ';
1542 } while (*++argv);
1543 p[-1] = '\0';
1544 return pi->cmdtext;
1545}
1546
Eric Andersenbafd94f2001-05-02 16:11:59 +00001547static void insert_bg_job(struct pipe *pi)
1548{
1549 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001550 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001551
1552 /* Linear search for the ID of the job to use */
1553 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001554 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001555 if (thejob->jobid >= pi->jobid)
1556 pi->jobid = thejob->jobid + 1;
1557
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001558 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001559 if (!G.job_list) {
1560 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001561 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001562 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001563 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001564 thejob->next = xmalloc(sizeof(*thejob));
1565 thejob = thejob->next;
1566 }
1567
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001568 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001569 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001570 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
1571 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
1572 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001573// TODO: do we really need to have so many fields which are just dead weight
1574// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001575 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001576 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001577 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001578 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001579 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001580
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001581 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001582 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001583 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
1584 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001585 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001586}
1587
Eric Andersenbafd94f2001-05-02 16:11:59 +00001588static void remove_bg_job(struct pipe *pi)
1589{
1590 struct pipe *prev_pipe;
1591
Denis Vlasenko87a86552008-07-29 19:43:10 +00001592 if (pi == G.job_list) {
1593 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001594 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00001595 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001596 while (prev_pipe->next != pi)
1597 prev_pipe = prev_pipe->next;
1598 prev_pipe->next = pi->next;
1599 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00001600 if (G.job_list)
1601 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00001602 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00001603 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001604}
Eric Andersen028b65b2001-06-28 01:10:11 +00001605
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001606/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001607static void delete_finished_bg_job(struct pipe *pi)
1608{
1609 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001610 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001611 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001612 free(pi);
1613}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001614#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001615
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001616/* Check to see if any processes have exited -- if they
1617 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001618static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001619{
Eric Andersenc798b072001-06-22 06:23:03 +00001620 int attributes;
1621 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001622#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001623 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001624#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001625 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001626 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001627
Eric Andersenc798b072001-06-22 06:23:03 +00001628 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001629 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00001630 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00001631
Denis Vlasenko1359da62007-04-21 23:27:30 +00001632/* Do we do this right?
1633 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001634 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001635 * [3]+ Stopped sleep 20 | false
1636 * bash-3.00# echo $?
1637 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1638 */
1639
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001640//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1641//are stopped. Testcase: "cat | cat" in a script (not on command line)
1642// + killall -STOP cat
1643
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001644 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00001645// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00001646 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001647 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001648 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001649#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00001650 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001651 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001652 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1653 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001654 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001655 childpid, WTERMSIG(status), WEXITSTATUS(status));
1656 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001657 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001658 childpid, WEXITSTATUS(status));
1659#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001660 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001661 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001662 for (i = 0; i < fg_pipe->num_cmds; i++) {
1663 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
1664 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001665 continue;
1666 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1667 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001668 fg_pipe->cmds[i].pid = 0;
1669 fg_pipe->alive_cmds--;
1670 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001671 /* last process gives overall exitstatus */
1672 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001673 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001674 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001675 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001676 fg_pipe->cmds[i].is_stopped = 1;
1677 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00001678 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001679 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
1680 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
1681 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001682 /* All processes in fg pipe have exited/stopped */
1683#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001684 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001685 insert_bg_job(fg_pipe);
1686#endif
1687 return rcode;
1688 }
1689 /* There are still running processes in the fg pipe */
1690 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00001691 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001692 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001693 }
1694
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001695#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001696 /* We asked to wait for bg or orphaned children */
1697 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001698 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001699 for (i = 0; i < pi->num_cmds; i++) {
1700 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001701 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001702 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001703 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001704 /* Happens when shell is used as init process (init=/bin/sh) */
1705 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001706 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00001707
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001708 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001709 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001710 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001711 pi->cmds[i].pid = 0;
1712 pi->alive_cmds--;
1713 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001714 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001715 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001716 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001717 }
1718 } else {
1719 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001720 pi->cmds[i].is_stopped = 1;
1721 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001722 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001723#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001724 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001725
Denis Vlasenko1359da62007-04-21 23:27:30 +00001726 /* wait found no children or failed */
1727
1728 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001729 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001730 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001731}
1732
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001733#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001734static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1735{
1736 pid_t p;
1737 int rcode = checkjobs(fg_pipe);
1738 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001739 p = getpgid(0); /* pgid of our process */
1740 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001741 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001742 return rcode;
1743}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001744#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001745
Denis Vlasenko05743d72008-02-10 12:10:08 +00001746/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001747 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001748 *
1749 * return code is normally -1, when the caller has to wait for children
1750 * to finish to determine the exit status of the pipe. If the pipe
1751 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00001752 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00001753 * return value.
1754 *
1755 * The input of the pipe is always stdin, the output is always
1756 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1757 * because it tries to avoid running the command substitution in
1758 * subshell, when that is in fact necessary. The subshell process
1759 * now has its stdout directed to the input of the appropriate pipe,
1760 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001761 *
1762 * Returns -1 only if started some children. IOW: we have to
1763 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001764 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001765static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001766{
1767 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001768 int nextin;
1769 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001770 struct command *command;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001771 char **ptrs2free = NULL;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001772 char **argv_expanded = NULL;
1773 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001774 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001775 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001776 /* it is not always needed, but we aim to smaller code */
1777 int squirrel[] = { -1, -1, -1 };
1778 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001779 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001780
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001781 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001782
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001783#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001784 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001785#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001786 pi->alive_cmds = 1;
1787 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001788
1789 /* Check if this is a simple builtin (not part of a pipe).
1790 * Builtins within pipes have to fork anyway, and are handled in
1791 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1792 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001793 command = &(pi->cmds[0]);
1794 if (single_and_fg && command->group && command->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001795 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001796 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001797 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001798 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00001799 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001800 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001801 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00001802 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001803 }
1804
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001805 argv = command->argv;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001806
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001807 if (single_and_fg && argv != NULL) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001808 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001809 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001810 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001811 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001812 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001813 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001814 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001815 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001816 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00001817 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001818
1819 /* Expand assignments into one string each */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001820 for (i = 0; i < command->assignment_cnt; i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001821 p = expand_string_to_string(argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001822 putenv(p);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001823 ptrs2free = add_malloced_string_to_strings(ptrs2free, p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001824 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001825
1826 /* Expand the rest into (possibly) many strings each */
1827 argv_expanded = expand_strvec_to_strvec(argv + i);
1828
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001829 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001830 if (strcmp(argv_expanded[0], x->cmd) == 0) {
1831 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001832 debug_printf("exec with redirects only\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001833 setup_redirects(command, NULL);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001834 rcode = EXIT_SUCCESS;
1835 goto clean_up_and_ret1;
Eric Andersen83a2ae22001-05-07 17:59:25 +00001836 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001837 debug_printf("builtin inline %s\n", argv_expanded[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001838 /* XXX setup_redirects acts on file descriptors, not FILEs.
1839 * This is perfect for work that comes after exec().
1840 * Is it really safe for inline use? Experimentally,
1841 * things seem to work with glibc. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001842 setup_redirects(command, squirrel);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001843 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001844 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001845 USE_FEATURE_SH_STANDALONE(clean_up_and_ret:)
Eric Andersen25f27032001-04-26 23:22:31 +00001846 restore_redirects(squirrel);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001847 clean_up_and_ret1:
1848 free_strings_and_unsetenv(ptrs2free, 1);
1849 free(argv_expanded);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001850 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001851 debug_printf_exec("run_pipe return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001852 return rcode;
1853 }
1854 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001855#if ENABLE_FEATURE_SH_STANDALONE
1856 {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001857 int a = find_applet_by_name(argv_expanded[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001858 if (a >= 0 && APPLET_IS_NOFORK(a)) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001859 setup_redirects(command, squirrel);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001860 save_nofork_data(&G.nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001861 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00001862 rcode = run_nofork_applet_prime(&G.nofork_save, a, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001863 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001864 }
1865 }
1866#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001867 }
1868
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001869 /* NB: argv_expanded may already be created, and that
1870 * might include `cmd` runs! Do not rerun it! We *must*
1871 * use argv_expanded if it's non-NULL */
1872
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001873 /* Disable job control signals for shell (parent) and
1874 * for initial child code after fork */
1875 set_jobctrl_sighandler(SIG_IGN);
1876
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001877 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001878 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001879 nextin = 0;
1880
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001881 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00001882#if !BB_MMU
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001883 /* Avoid confusion WHAT is volatile. Pointer is volatile,
1884 * not the stuff it points to. */
1885 typedef char **ppchar_t;
1886 volatile ppchar_t shared_across_vfork;
Denis Vlasenko76d50412008-06-10 16:19:39 +00001887#endif
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001888
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001889 command = &(pi->cmds[i]);
1890 if (command->argv) {
1891 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001892 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001893 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001894
1895 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001896 pipefds[0] = 0;
1897 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001898 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001899 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001900
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001901#if !BB_MMU
1902 shared_across_vfork = ptrs2free;
1903#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001904 command->pid = BB_MMU ? fork() : vfork();
1905 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00001906 if (ENABLE_HUSH_JOB)
1907 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001908#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001909 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00001910 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001911 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001912 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001913 /* Don't do pgrp restore anymore on fatal signals */
1914 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001915 pgrp = pi->pgrp;
1916 if (pgrp < 0) /* true for 1st process only */
1917 pgrp = getpid();
1918 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001919 /* We do it in *every* child, not just first,
1920 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001921 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001922 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001923 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001924#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00001925 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001926 xmove_fd(pipefds[1], 1); /* write end */
1927 if (pipefds[0] > 1)
1928 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00001929 /* Like bash, explicit redirects override pipes,
1930 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001931 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001932
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001933 /* Restore default handlers just prior to exec */
1934 set_jobctrl_sighandler(SIG_DFL);
1935 set_misc_sighandler(SIG_DFL);
1936 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001937/* comment how it sets env????
1938for single_and_fg, it's already set yes? */
1939 pseudo_exec((char ***) &shared_across_vfork, command, argv_expanded);
1940 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00001941 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001942 /* parent */
1943#if !BB_MMU
1944 ptrs2free = shared_across_vfork;
1945#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001946 free(argv_expanded);
1947 argv_expanded = NULL;
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001948 free_strings_and_unsetenv(ptrs2free, 1);
1949 ptrs2free = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001950 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001951 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00001952 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001953 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001954 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001955#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001956 /* Second and next children need to know pid of first one */
1957 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001958 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001959#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001960 }
Eric Andersen25f27032001-04-26 23:22:31 +00001961
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001962 if (i)
1963 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001964 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001965 close(pipefds[1]); /* write end */
1966 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00001967 nextin = pipefds[0];
1968 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001969
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001970 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001971 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
1972 return 1;
1973 }
1974
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001975 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00001976 return -1;
1977}
1978
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001979#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001980static void debug_print_tree(struct pipe *pi, int lvl)
1981{
1982 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001983 [PIPE_SEQ] = "SEQ",
1984 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001985 [PIPE_OR ] = "OR" ,
1986 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001987 };
1988 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001989 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001990#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001991 [RES_IF ] = "IF" ,
1992 [RES_THEN ] = "THEN" ,
1993 [RES_ELIF ] = "ELIF" ,
1994 [RES_ELSE ] = "ELSE" ,
1995 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001996#endif
1997#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001998 [RES_FOR ] = "FOR" ,
1999 [RES_WHILE] = "WHILE",
2000 [RES_UNTIL] = "UNTIL",
2001 [RES_DO ] = "DO" ,
2002 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002003#endif
2004#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002005 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002006#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002007#if ENABLE_HUSH_CASE
2008 [RES_CASE ] = "CASE" ,
2009 [RES_MATCH] = "MATCH",
2010 [RES_CASEI] = "CASEI",
2011 [RES_ESAC ] = "ESAC" ,
2012#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002013 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002014 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002015 };
2016
2017 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002018
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002019 pin = 0;
2020 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002021 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2022 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002023 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002024 while (prn < pi->num_cmds) {
2025 struct command *command = &pi->cmds[prn];
2026 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002027
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002028 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2029 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002030 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002031 (command->subshell ? "()" : "{}"),
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002032 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002033 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002034 prn++;
2035 continue;
2036 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002037 if (argv) while (*argv) {
2038 fprintf(stderr, " '%s'", *argv);
2039 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002040 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002041 fprintf(stderr, "\n");
2042 prn++;
2043 }
2044 pi = pi->next;
2045 pin++;
2046 }
2047}
2048#endif
2049
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002050/* NB: called by pseudo_exec, and therefore must not modify any
2051 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002052static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002053{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002054#if ENABLE_HUSH_CASE
2055 char *case_word = NULL;
2056#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002057#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002058 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002059 char *for_varname = NULL;
2060 char **for_lcur = NULL;
2061 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002062#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002063 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002064 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002065#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002066 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002067#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002068 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002069#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002070 /*enum reserved_style*/ smallint rword = RES_NONE;
2071 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002072
Denis Vlasenko87a86552008-07-29 19:43:10 +00002073 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002074
Denis Vlasenko06810332007-05-21 23:30:54 +00002075#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002076 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002077 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2078 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002079 continue;
2080 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002081 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002082 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002083 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002084 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002085 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002086 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002087 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002088 continue;
2089 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002090 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2091 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002092 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002093 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002094 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002095 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002096 }
2097 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002098#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002099
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002100 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002101 * in order to return, no direct "return" statements please.
2102 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002103
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002104#if ENABLE_HUSH_JOB
2105 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2106 * We are saving state before entering outermost list ("while...done")
2107 * so that ctrl-Z will correctly background _entire_ outermost list,
2108 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002109 if (++G.run_list_level == 1 && G.interactive_fd) {
2110 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002111 /* ctrl-Z forked and we are parent; or ctrl-C.
2112 * Sighandler has longjmped us here */
2113 signal(SIGINT, SIG_IGN);
2114 signal(SIGTSTP, SIG_IGN);
2115 /* Restore level (we can be coming from deep inside
2116 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002117 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002118#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002119 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002120 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002121 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002122 }
2123#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002124 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002125 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2126 * Remember this child as background job */
2127 insert_bg_job(pi);
2128 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002129 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002130 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002131 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002132 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002133 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002134 rcode = 0;
2135 goto ret;
2136 }
2137 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002138 G.toplevel_list = pi;
2139 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002140#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002141 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002142#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002143 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002144 signal(SIGINT, handler_ctrl_c);
2145 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002146#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002147
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002148 /* Go through list of pipes, (maybe) executing them. */
2149 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002150 IF_HAS_KEYWORDS(rword = pi->res_word;)
2151 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002152 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2153 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002154#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002155 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002156 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002157 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002158 /* start of a loop: remember where loop starts */
2159 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002160 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002161 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002162#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002163 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002164 if (pi->followup == PIPE_SEQ)
2165 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002166 /* it is "<false> && CMD" or "<true> || CMD"
2167 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002168 continue;
2169 }
2170 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002171 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002172#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002173 if (cond_code) {
2174 if (rword == RES_THEN) {
2175 /* "if <false> THEN cmd": skip cmd */
2176 continue;
2177 }
2178 } else {
2179 if (rword == RES_ELSE || rword == RES_ELIF) {
2180 /* "if <true> then ... ELSE/ELIF cmd":
2181 * skip cmd and all following ones */
2182 break;
2183 }
2184 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002185#endif
2186#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002187 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002188 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002189 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002190
2191 static const char encoded_dollar_at[] ALIGN1 = {
2192 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2193 }; /* encoded representation of "$@" */
2194 static const char *const encoded_dollar_at_argv[] = {
2195 encoded_dollar_at, NULL
2196 }; /* argv list with one element: "$@" */
2197 char **vals;
2198
2199 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002200 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002201 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002202 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002203 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002204 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002205 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002206 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002207 debug_print_strings("for_list made from", vals);
2208 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002209 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002210 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002211 for_varname = pi->cmds[0].argv[0];
2212 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002213 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002214 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002215 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002216 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002217 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002218 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002219 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002220 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002221 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002222 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002223 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002224//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002225 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2226 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002227 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002228 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002229 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002230 if (rword == RES_DONE) {
2231 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002232 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002233#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002234#if ENABLE_HUSH_CASE
2235 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002236 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002237 continue;
2238 }
2239 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002240 char **argv;
2241
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002242 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2243 break;
2244 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002245 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002246 while (*argv) {
2247 char *pattern = expand_string_to_string(*argv);
2248 /* TODO: which FNM_xxx flags to use? */
2249 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2250 free(pattern);
2251 if (cond_code == 0) { /* match! we will execute this branch */
2252 free(case_word); /* make future "word)" stop */
2253 case_word = NULL;
2254 break;
2255 }
2256 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002257 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002258 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002259 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002260 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002261 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002262 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002263 }
2264#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002265 if (pi->num_cmds == 0)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002266 continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002267
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002268 /* After analyzing all keywords and conditions, we decided
2269 * to execute this pipe. NB: has to do checkjobs(NULL)
2270 * after run_pipe() to collect any background children,
2271 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002272 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002273 {
2274 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002275#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002276 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002277#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002278 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2279 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002280 /* we only ran a builtin: rcode is already known
2281 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002282#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002283 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002284 if (G.flag_break_continue) {
2285 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002286 /* we might fall into outer *loop*,
2287 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002288 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002289 G.depth_break_continue--;
2290 if (G.depth_break_continue == 0)
2291 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002292 /* else: e.g. "continue 2" should *break* once, *then* continue */
2293 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002294 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002295 goto check_jobs_and_break;
2296 /* "continue": simulate end of loop */
2297 rword = RES_DONE;
2298 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002299 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002300#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002301 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002302 /* what does bash do with attempts to background builtins? */
2303 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002304 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2305 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002306#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002307 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002308 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002309#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002310 rcode = 0; /* EXIT_SUCCESS */
2311 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002312#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002313 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002314 /* waits for completion, then fg's main shell */
2315 rcode = checkjobs_and_fg_shell(pi);
2316 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2317 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002318#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002319 { /* this one just waits for completion */
2320 rcode = checkjobs(pi);
2321 debug_printf_exec(": checkjobs returned %d\n", rcode);
2322 }
Eric Andersen25f27032001-04-26 23:22:31 +00002323 }
2324 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002325 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002326 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002327
2328 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002329#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002330 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002331 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002332#endif
2333#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002334 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002335 if (rcode) {
2336 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002337 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002338 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002339 }
2340 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002341 if (!rcode) {
2342 check_jobs_and_break:
2343 checkjobs(NULL);
2344 break;
2345 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002346 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002347#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002348 if ((rcode == 0 && pi->followup == PIPE_OR)
2349 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002350 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002351 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002352 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002353 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002354 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002355
2356#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002357 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002358 /* ctrl-Z forked somewhere in the past, we are the child,
2359 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002360//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002361 exit(rcode);
2362 }
2363 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002364 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002365 signal(SIGTSTP, SIG_IGN);
2366 signal(SIGINT, SIG_IGN);
2367 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002368#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002369 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002370#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002371 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002372 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002373 free(for_list);
2374#endif
2375#if ENABLE_HUSH_CASE
2376 free(case_word);
2377#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002378 return rcode;
2379}
2380
Eric Andersen25f27032001-04-26 23:22:31 +00002381/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002382static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002383{
2384 char **p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002385 struct command *command;
Eric Andersen25f27032001-04-26 23:22:31 +00002386 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002387 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002388
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002389 if (pi->stopped_cmds > 0)
Eric Andersen52a97ca2001-06-22 06:49:26 +00002390 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002391 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002392 for (i = 0; i < pi->num_cmds; i++) {
2393 command = &pi->cmds[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002394 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002395 if (command->argv) {
2396 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002397 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002398 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002399 free_strings(command->argv);
2400 command->argv = NULL;
2401 } else if (command->group) {
2402 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), command->subshell);
2403 ret_code = free_pipe_list(command->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002404 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002405 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002406 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002407 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002408 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko211b59b2008-06-23 16:28:53 +00002409 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002410 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002411 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002412 if (r->rd_filename) {
2413 debug_printf_clean(" %s\n", r->rd_filename);
2414 free(r->rd_filename);
2415 r->rd_filename = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002416 }
Eric Andersen25f27032001-04-26 23:22:31 +00002417 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002418 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002419 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002420 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002421 free(r);
2422 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002423 command->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002424 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002425 free(pi->cmds); /* children are an array, they get freed all at once */
2426 pi->cmds = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002427#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002428 free(pi->cmdtext);
2429 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002430#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002431 return ret_code;
2432}
2433
Eric Andersenbf7df042001-05-23 22:18:35 +00002434static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002435{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002436 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002437 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002438
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002439 for (pi = head; pi; pi = next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002440#if HAS_KEYWORDS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002441 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002442#endif
Eric Andersenbf7df042001-05-23 22:18:35 +00002443 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002444 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002445 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002446 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002447 free(pi);
2448 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002449 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002450}
2451
2452/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002453static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002454{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002455 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002456 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002457 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002458 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002459 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002460 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002461 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002462 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002463 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002464 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002465 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002466 return rcode;
2467}
2468
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002469
Denis Vlasenko170435c2007-05-23 13:01:10 +00002470/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002471 * all variable references within and returns a pointer to
2472 * a list of expanded strings, possibly with larger number
2473 * of strings. (Think VAR="a b"; echo $VAR).
2474 * This new list is allocated as a single malloc block.
2475 * NULL-terminated list of char* pointers is at the beginning of it,
2476 * followed by strings themself.
2477 * Caller can deallocate entire list by single free(list). */
2478
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002479/* Store given string, finalizing the word and starting new one whenever
Denis Vlasenko87a86552008-07-29 19:43:10 +00002480 * we encounter IFS char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002481 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002482static int expand_on_ifs(o_string *output, int n, const char *str)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002483{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002484 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002485 int word_len = strcspn(str, G.ifs);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002486 if (word_len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002487 if (output->o_quote || !output->o_glob)
2488 o_addQstr(output, str, word_len);
2489 else /* protect backslashes against globbing up :) */
2490 o_addstr_duplicate_backslash(output, str, word_len);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002491 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002492 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002493 if (!*str) /* EOL - do not finalize word */
2494 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002495 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002496 debug_print_list("expand_on_ifs", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002497 n = o_save_ptr(output, n);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002498 str += strspn(str, G.ifs); /* skip ifs chars */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002499 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002500 debug_print_list("expand_on_ifs[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002501 return n;
2502}
2503
2504/* Expand all variable references in given string, adding words to list[]
2505 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2506 * to be filled). This routine is extremely tricky: has to deal with
2507 * variables/parameters with whitespace, $* and $@, and constructs like
2508 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002509static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002510{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002511 /* or_mask is either 0 (normal case) or 0x80
Denis Vlasenko55789c62008-06-18 16:30:42 +00002512 * (expansion of right-hand side of assignment == 1-element expand.
2513 * It will also do no globbing, and thus we must not backslash-quote!) */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002514
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002515 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002516 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002517 const char *val;
2518 char *p;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002519
2520 ored_ch = 0;
2521
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002522 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002523 debug_print_list("expand_vars_to_list", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002524 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002525 debug_print_list("expand_vars_to_list[0]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002526
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002527 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002528#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002529 o_string subst_result = NULL_O_STRING;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002530#endif
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002531
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002532 o_addstr(output, arg, p - arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002533 debug_print_list("expand_vars_to_list[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002534 arg = ++p;
2535 p = strchr(p, SPECIAL_VAR_SYMBOL);
2536
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002537 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002538 /* "$@" is special. Even if quoted, it can still
2539 * expand to nothing (not even an empty string) */
2540 if ((first_ch & 0x7f) != '@')
2541 ored_ch |= first_ch;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002542 val = NULL;
2543 switch (first_ch & 0x7f) {
2544 /* Highest bit in first_ch indicates that var is double-quoted */
2545 case '$': /* pid */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002546 val = utoa(G.root_pid);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002547 break;
2548 case '!': /* bg pid */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002549 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002550 break;
2551 case '?': /* exitcode */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002552 val = utoa(G.last_return_code);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002553 break;
2554 case '#': /* argc */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002555 val = utoa(G.global_argc ? G.global_argc-1 : 0);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002556 break;
2557 case '*':
2558 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002559 i = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002560 if (!G.global_argv[i])
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002561 break;
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00002562 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002563 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002564 smallint sv = output->o_quote;
2565 /* unquoted var's contents should be globbed, so don't quote */
2566 output->o_quote = 0;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002567 while (G.global_argv[i]) {
2568 n = expand_on_ifs(output, n, G.global_argv[i]);
2569 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2570 if (G.global_argv[i++][0] && G.global_argv[i]) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002571 /* this argv[] is not empty and not last:
2572 * put terminating NUL, start new word */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002573 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002574 debug_print_list("expand_vars_to_list[2]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002575 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002576 debug_print_list("expand_vars_to_list[3]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002577 }
2578 }
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002579 output->o_quote = sv;
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002580 } else
2581 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002582 * and in this case should treat it like '$*' - see 'else...' below */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002583 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002584 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002585 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2586 if (++i >= G.global_argc)
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002587 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002588 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002589 debug_print_list("expand_vars_to_list[4]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002590 n = o_save_ptr(output, n);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002591 }
2592 } else { /* quoted $*: add as one word */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002593 while (1) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002594 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2595 if (!G.global_argv[++i])
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002596 break;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002597 if (G.ifs[0])
2598 o_addchr(output, G.ifs[0]);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002599 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002600 }
2601 break;
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002602 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2603 /* "Empty variable", used to make "" etc to not disappear */
2604 arg++;
2605 ored_ch = 0x80;
2606 break;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002607#if ENABLE_HUSH_TICK
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002608 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002609 struct in_str input;
2610 *p = '\0';
2611 arg++;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002612//TODO: can we just stuff it into "output" directly?
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002613 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002614 setup_string_in_str(&input, arg);
2615 process_command_subs(&subst_result, &input, NULL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002616 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002617 val = subst_result.data;
2618 goto store_val;
2619 }
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002620#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002621 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002622 *p = '\0';
2623 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002624 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002625 i = xatoi_u(arg);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002626 if (i < G.global_argc)
2627 val = G.global_argv[i];
Denis Vlasenko55789c62008-06-18 16:30:42 +00002628 /* else val remains NULL: $N with too big N */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002629 } else
2630 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002631 arg[0] = first_ch;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002632#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002633 store_val:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002634#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002635 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002636 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002637 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002638 if (val) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002639 /* unquoted var's contents should be globbed, so don't quote */
2640 smallint sv = output->o_quote;
2641 output->o_quote = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002642 n = expand_on_ifs(output, n, val);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002643 val = NULL;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002644 output->o_quote = sv;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002645 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002646 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002647 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002648 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002649 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002650 if (val) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002651 o_addQstr(output, val, strlen(val));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002652 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002653
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002654#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002655 o_free(&subst_result);
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002656#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002657 arg = ++p;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002658 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2659
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002660 if (arg[0]) {
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002661 debug_print_list("expand_vars_to_list[a]", output, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002662 /* this part is literal, and it was already pre-quoted
2663 * if needed (much earlier), do not use o_addQstr here! */
2664 o_addstr(output, arg, strlen(arg) + 1);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002665 debug_print_list("expand_vars_to_list[b]", output, n);
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002666 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2667 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2668 ) {
2669 n--;
2670 /* allow to reuse list[n] later without re-growth */
2671 output->has_empty_slot = 1;
2672 } else {
2673 o_addchr(output, '\0');
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002674 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002675 return n;
2676}
2677
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002678static char **expand_variables(char **argv, int or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002679{
2680 int n;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002681 char **list;
2682 char **v;
2683 o_string output = NULL_O_STRING;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002684
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002685 if (or_mask & 0x100) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002686 output.o_quote = 1; /* protect against globbing for "$var" */
2687 /* (unquoted $var will temporarily switch it off) */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002688 output.o_glob = 1;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002689 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002690
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002691 n = 0;
2692 v = argv;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002693 while (*v) {
2694 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2695 v++;
2696 }
2697 debug_print_list("expand_variables", &output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002698
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002699 /* output.data (malloced in one block) gets returned in "list" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002700 list = o_finalize_list(&output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002701 debug_print_strings("expand_variables[1]", list);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002702 return list;
2703}
2704
Denis Vlasenko170435c2007-05-23 13:01:10 +00002705static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002706{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002707 return expand_variables(argv, 0x100);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002708}
2709
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002710/* Used for expansion of right hand of assignments */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002711/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2712 * "v=/bin/c*" */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002713static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002714{
2715 char *argv[2], **list;
2716
2717 argv[0] = (char*)str;
2718 argv[1] = NULL;
2719 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002720 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002721 if (!list[0] || list[1])
2722 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002723 /* actually, just move string 2*sizeof(char*) bytes back */
2724 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002725 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2726 return (char*)list;
2727}
2728
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002729/* Used for "eval" builtin */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002730static char* expand_strvec_to_string(char **argv)
2731{
2732 char **list;
2733
2734 list = expand_variables(argv, 0x80);
2735 /* Convert all NULs to spaces */
2736 if (list[0]) {
2737 int n = 1;
2738 while (list[n]) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002739 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002740 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2741 bb_error_msg_and_die("BUG in varexp3");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002742 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002743 n++;
2744 }
2745 }
2746 strcpy((char*)list, list[0]);
2747 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002748 return (char*)list;
2749}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002750
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002751
2752/* Used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002753static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002754{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002755 struct variable *cur;
2756 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002757
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002758 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002759 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002760 len = strlen(name);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002761 for (cur = G.top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002762 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002763 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002764 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002765 return NULL;
2766}
2767
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002768/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002769 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002770static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002771{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002772 struct variable *cur;
2773 char *value;
2774 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002775
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002776 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002777 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002778 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002779 return -1;
2780 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002781
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002782 name_len = value - str + 1; /* including '=' */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002783 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002784 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002785 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002786 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002787 /* Bail out. Note that now cur points
2788 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002789 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002790 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002791 cur = cur->next;
2792 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002793 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002794 /* We found an existing var with this name */
2795 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002796 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002797 bb_error_msg("%s: readonly variable", str);
2798 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002799 return -1;
2800 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002801 unsetenv(str); /* just in case */
2802 *value = '=';
2803 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002804 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002805 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002806 goto exp;
2807 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002808 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002809 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002810 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002811 goto free_and_exp;
2812 }
2813 /* max_len == 0 signifies "malloced" var, which we can
2814 * (and has to) free */
2815 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002816 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002817 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002818 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002819 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002820
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002821 /* Not found - create next variable struct */
2822 cur->next = xzalloc(sizeof(*cur));
2823 cur = cur->next;
2824
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002825 set_str_and_exp:
2826 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002827 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002828 if (flg_export)
2829 cur->flg_export = 1;
2830 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002831 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002832 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002833}
2834
Eric Andersenf72f5622001-05-15 23:21:41 +00002835static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002836{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002837 struct variable *cur;
2838 struct variable *prev = prev; /* for gcc */
2839 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002840
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002841 if (!name)
2842 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002843 name_len = strlen(name);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002844 cur = G.top_var;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002845 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002846 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002847 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002848 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002849 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002850 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002851 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2852 * is ro, and we cannot reach this code on the 1st pass */
2853 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002854 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002855 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002856 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002857 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002858 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002859 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002860 prev = cur;
2861 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002862 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002863}
2864
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002865/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00002866 * for file descriptor duplication, e.g., "2>&1".
2867 * Return code is 0 normally, 1 if a syntax error is detected in src.
2868 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002869static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00002870 struct in_str *input)
2871{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002872 struct command *command = ctx->command;
2873 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002874 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002875
2876 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002877 while (redir) {
2878 last_redir = redir;
2879 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002880 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002881 redir = xzalloc(sizeof(struct redir_struct));
2882 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002883 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002884 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002885 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002886 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002887 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002888 }
2889
Denis Vlasenko55789c62008-06-18 16:30:42 +00002890 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002891 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002892
2893 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2894
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002895 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002896 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002897 if (redir->dup == -2)
2898 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002899 if (redir->dup != -1) {
2900 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002901 * is legit; I postpone that to "run time"
2902 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002903 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2904 } else {
2905 /* We do _not_ try to open the file that src points to,
2906 * since we need to return and let src be expanded first.
2907 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002908 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002909 ctx->pending_redirect = redir;
2910 }
2911 return 0;
2912}
2913
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002914static struct pipe *new_pipe(void)
2915{
Eric Andersen25f27032001-04-26 23:22:31 +00002916 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002917 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002918 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002919 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002920 return pi;
2921}
2922
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002923static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002924{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002925 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002926 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002927 /* Create the memory for command, roughly:
2928 * ctx->pipe->cmds = new struct command;
2929 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002930 */
2931 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002932}
2933
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002934/* If a reserved word is found and processed, parse context is modified
2935 * and 1 is returned.
2936 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00002937 * case, function, and select are obnoxious, save those for later.
2938 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002939#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002940struct reserved_combo {
2941 char literal[6];
2942 unsigned char res;
2943 unsigned char assignment_flag;
2944 int flag;
2945};
2946enum {
2947 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002948#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002949 FLAG_IF = (1 << RES_IF ),
2950 FLAG_THEN = (1 << RES_THEN ),
2951 FLAG_ELIF = (1 << RES_ELIF ),
2952 FLAG_ELSE = (1 << RES_ELSE ),
2953 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002954#endif
2955#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002956 FLAG_FOR = (1 << RES_FOR ),
2957 FLAG_WHILE = (1 << RES_WHILE),
2958 FLAG_UNTIL = (1 << RES_UNTIL),
2959 FLAG_DO = (1 << RES_DO ),
2960 FLAG_DONE = (1 << RES_DONE ),
2961 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002962#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002963#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002964 FLAG_MATCH = (1 << RES_MATCH),
2965 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002966#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002967 FLAG_START = (1 << RES_XXXX ),
2968};
2969
2970static const struct reserved_combo* match_reserved_word(o_string *word)
2971{
Eric Andersen25f27032001-04-26 23:22:31 +00002972 /* Mostly a list of accepted follow-up reserved words.
2973 * FLAG_END means we are done with the sequence, and are ready
2974 * to turn the compound list into a command.
2975 * FLAG_START means the word must start a new compound list.
2976 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002977 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002978#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002979 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
2980 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
2981 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2982 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
2983 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
2984 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002985#endif
2986#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002987 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
2988 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2989 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
2990 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
2991 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
2992 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002993#endif
2994#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00002995 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
2996 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002997#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002998 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00002999 const struct reserved_combo *r;
3000
3001 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3002 if (strcmp(word->data, r->literal) == 0)
3003 return r;
3004 }
3005 return NULL;
3006}
3007static int reserved_word(o_string *word, struct parse_context *ctx)
3008{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003009#if ENABLE_HUSH_CASE
3010 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003011 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003012 };
3013#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003014 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003015
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003016 r = match_reserved_word(word);
3017 if (!r)
3018 return 0;
3019
3020 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003021#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003022 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3023 /* "case word IN ..." - IN part starts first match part */
3024 r = &reserved_match;
3025 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003026#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003027 if (r->flag == 0) { /* '!' */
3028 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003029 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003030 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003031 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003032 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003033 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003034 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003035 if (r->flag & FLAG_START) {
3036 struct parse_context *new;
3037 debug_printf("push stack\n");
3038 new = xmalloc(sizeof(*new));
3039 *new = *ctx; /* physical copy */
3040 initialize_context(ctx);
3041 ctx->stack = new;
3042 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3043 syntax(NULL);
3044 ctx->ctx_res_w = RES_SNTX;
3045 return 1;
3046 }
3047 ctx->ctx_res_w = r->res;
3048 ctx->old_flag = r->flag;
3049 if (ctx->old_flag & FLAG_END) {
3050 struct parse_context *old;
3051 debug_printf("pop stack\n");
3052 done_pipe(ctx, PIPE_SEQ);
3053 old = ctx->stack;
3054 old->command->group = ctx->list_head;
3055 old->command->subshell = 0;
3056 *ctx = *old; /* physical copy */
3057 free(old);
3058 }
3059 word->o_assignment = r->assignment_flag;
3060 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003061}
Denis Vlasenko06810332007-05-21 23:30:54 +00003062#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003063
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003064/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003065 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003066static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003067{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003068 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003069
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003070 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003071 if (word->length == 0 && word->nonnull == 0) {
3072 debug_printf_parse("done_word return 0: true null, ignored\n");
3073 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003074 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003075 /* If this word wasn't an assignment, next ones definitely
3076 * can't be assignments. Even if they look like ones. */
3077 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3078 && word->o_assignment != WORD_IS_KEYWORD
3079 ) {
3080 word->o_assignment = NOT_ASSIGNMENT;
3081 } else {
3082 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003083 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003084 word->o_assignment = MAYBE_ASSIGNMENT;
3085 }
3086
Eric Andersen25f27032001-04-26 23:22:31 +00003087 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003088 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3089 * only if run as "bash", not "sh" */
3090 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003091 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003092 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003093 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003094 /* "{ echo foo; } echo bar" - bad */
3095 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003096 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003097 syntax(NULL);
3098 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3099 return 1;
3100 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003101#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003102#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003103 if (ctx->ctx_dsemicolon
3104 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3105 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003106 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003107 /* ctx->ctx_res_w = RES_MATCH; */
3108 ctx->ctx_dsemicolon = 0;
3109 } else
3110#endif
3111
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003112 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003113#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003114 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3115 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003116#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003117 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003118 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3119 if (reserved_word(word, ctx)) {
3120 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003121 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3122 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003123 }
Eric Andersen25f27032001-04-26 23:22:31 +00003124 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003125#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003126 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003127 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3128 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003129 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003130 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003131 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003132 char *p = word->data;
3133 while (p[0] == SPECIAL_VAR_SYMBOL
3134 && (p[1] & 0x7f) == '@'
3135 && p[2] == SPECIAL_VAR_SYMBOL
3136 ) {
3137 p += 3;
3138 }
3139 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003140 /* saw no "$@", or not only "$@" but some
3141 * real text is there too */
3142 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003143 * e.g. "", $empty"" etc to not disappear */
3144 o_addchr(word, SPECIAL_VAR_SYMBOL);
3145 o_addchr(word, SPECIAL_VAR_SYMBOL);
3146 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003147 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003148 command->argv = add_malloced_string_to_strings(command->argv, xstrdup(word->data));
3149 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003150 }
Eric Andersen25f27032001-04-26 23:22:31 +00003151
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003152 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003153 ctx->pending_redirect = NULL;
3154
Denis Vlasenko06810332007-05-21 23:30:54 +00003155#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003156 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003157 /* NB: basically, this makes hush see "for v in ..." syntax as if
3158 * as it is "for v; in ...". FOR and IN become two pipe structs
3159 * in parse tree. */
3160 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003161//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003162 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003163 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003164#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003165#if ENABLE_HUSH_CASE
3166 /* Force CASE to have just one word */
3167 if (ctx->ctx_res_w == RES_CASE) {
3168 done_pipe(ctx, PIPE_SEQ);
3169 }
3170#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003171 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003172 return 0;
3173}
3174
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003175/* Command (member of a pipe) is complete. The only possible error here
3176 * is out of memory, in which case xmalloc exits. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003177static int done_command(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003178{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003179 /* The command is really already in the pipe structure, so
3180 * advance the pipe counter and make a new, null command. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003181 struct pipe *pi = ctx->pipe;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003182 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003183
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003184 if (command) {
3185 if (command->group == NULL
3186 && command->argv == NULL
3187 && command->redirects == NULL
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003188 ) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003189 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3190 return pi->num_cmds;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003191 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003192 pi->num_cmds++;
3193 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003194 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003195 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003196 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003197
3198 /* Only real trickiness here is that the uncommitted
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003199 * command structure is not counted in pi->num_cmds. */
3200 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3201 command = &pi->cmds[pi->num_cmds];
3202 memset(command, 0, sizeof(*command));
Eric Andersen25f27032001-04-26 23:22:31 +00003203
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003204 ctx->command = command;
Eric Andersen25f27032001-04-26 23:22:31 +00003205 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003206
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003207 return pi->num_cmds; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003208}
3209
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003210static void done_pipe(struct parse_context *ctx, pipe_style type)
Eric Andersen25f27032001-04-26 23:22:31 +00003211{
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003212 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003213
3214 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenko395ae452008-07-14 06:29:38 +00003215 /* Close previous command */
3216 not_null = done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003217 ctx->pipe->followup = type;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003218 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3219 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003220 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
Denis Vlasenko395ae452008-07-14 06:29:38 +00003221
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003222 /* Without this check, even just <enter> on command line generates
3223 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003224 * IOW: it is safe to do it unconditionally.
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003225 * RES_NONE case is for "for a in; do ..." (empty IN set)
3226 * to work, possibly other cases too. */
3227 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003228 struct pipe *new_p;
3229 debug_printf_parse("done_pipe: adding new pipe: "
Denis Vlasenko757361f2008-07-14 08:26:47 +00003230 "not_null:%d ctx->ctx_res_w:%d\n",
Denis Vlasenko395ae452008-07-14 06:29:38 +00003231 not_null, ctx->ctx_res_w);
3232 new_p = new_pipe();
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003233 ctx->pipe->next = new_p;
3234 ctx->pipe = new_p;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003235 ctx->command = NULL; /* needed! */
Denis Vlasenko395ae452008-07-14 06:29:38 +00003236 /* RES_THEN, RES_DO etc are "sticky" -
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003237 * they remain set for commands inside if/while.
3238 * This is used to control execution.
3239 * RES_FOR and RES_IN are NOT sticky (needed to support
3240 * cases where variable or value happens to match a keyword):
3241 */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003242#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003243 if (ctx->ctx_res_w == RES_FOR
3244 || ctx->ctx_res_w == RES_IN)
3245 ctx->ctx_res_w = RES_NONE;
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003246#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003247#if ENABLE_HUSH_CASE
3248 if (ctx->ctx_res_w == RES_MATCH)
3249 ctx->ctx_res_w = RES_CASEI;
3250#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003251 /* Create the memory for command, roughly:
3252 * ctx->pipe->cmds = new struct command;
3253 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003254 */
3255 done_command(ctx);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003256 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003257 debug_printf_parse("done_pipe return\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003258}
3259
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003260/* Peek ahead in the in_str to find out if we have a "&n" construct,
Eric Andersen25f27032001-04-26 23:22:31 +00003261 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003262 * Return either -2 (syntax error), -1 (no &), or the number found.
Eric Andersen25f27032001-04-26 23:22:31 +00003263 */
3264static int redirect_dup_num(struct in_str *input)
3265{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003266 int ch, d = 0, ok = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003267 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003268 if (ch != '&') return -1;
3269
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003270 i_getch(input); /* get the & */
3271 ch = i_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003272 if (ch == '-') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003273 i_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003274 return -3; /* "-" represents "close me" */
3275 }
3276 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003277 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003278 ok = 1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003279 i_getch(input);
3280 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003281 }
3282 if (ok) return d;
3283
Manuel Novoa III cad53642003-03-19 09:13:01 +00003284 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003285 return -2;
3286}
3287
3288/* If a redirect is immediately preceded by a number, that number is
3289 * supposed to tell which file descriptor to redirect. This routine
3290 * looks for such preceding numbers. In an ideal world this routine
3291 * needs to handle all the following classes of redirects...
3292 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3293 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3294 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3295 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3296 * A -1 output from this program means no valid number was found, so the
3297 * caller should use the appropriate default for this redirection.
3298 */
3299static int redirect_opt_num(o_string *o)
3300{
3301 int num;
3302
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003303 if (o->length == 0)
3304 return -1;
3305 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003306 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003307 return -1;
3308 }
3309 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003310 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003311 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003312 return num;
3313}
3314
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003315#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003316static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003317{
3318 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003319 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003320
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003321 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003322/* *** NOMMU WARNING *** */
3323/* By using vfork here, we suspend parent till child exits or execs.
3324 * If child will not do it before it fills the pipe, it can block forever
3325 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003326 * Try this script:
3327 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3328 * huge=`cat TESTFILE` # will block here forever
3329 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003330 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003331 pid = BB_MMU ? fork() : vfork();
3332 if (pid < 0)
3333 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003334 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003335 if (ENABLE_HUSH_JOB)
3336 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003337 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003338 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003339 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003340#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003341 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003342#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003343 /* Process substitution is not considered to be usual
3344 * 'command execution'.
3345 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3346 /* Not needed, we are relying on it being disabled
3347 * everywhere outside actual command execution. */
3348 /*set_jobctrl_sighandler(SIG_IGN);*/
3349 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003350 /* Freeing 'head' here would break NOMMU. */
3351 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003352 }
Eric Andersen25f27032001-04-26 23:22:31 +00003353 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003354 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003355 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003356 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003357}
3358
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003359/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003360static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003361 struct in_str *input,
3362 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003363{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003364 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003365 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003366 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003367 FILE *p;
3368 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003369
Eric Andersen25f27032001-04-26 23:22:31 +00003370 initialize_context(&inner);
3371
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003372 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003373 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003374 if (retcode != 0)
3375 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003376 done_word(&result, &inner);
3377 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003378 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003379
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003380 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003381 if (p == NULL)
3382 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003383 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003384 setup_file_in_str(&pipe_str, p);
3385
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003386 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003387 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003388 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003389 if (ch == '\n') {
3390 eol_cnt++;
3391 continue;
3392 }
3393 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003394 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003395 eol_cnt--;
3396 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003397 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003398 }
3399
3400 debug_printf("done reading from pipe, pclose()ing\n");
3401 /* This is the step that wait()s for the child. Should be pretty
3402 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003403 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003404 * at the same time. That would be a lot of work, and contrary
3405 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003406 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003407 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003408 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003409 return retcode;
3410}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003411#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003412
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003413static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003414 struct in_str *input, int ch)
3415{
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003416 /* NB: parse_group may create and use its own o_string,
3417 * without any code changes. It just so happens that code is smaller
3418 * if we (ab)use caller's one. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003419 int rcode;
3420 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003421 struct parse_context sub;
3422 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003423
3424 debug_printf_parse("parse_group entered\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003425 if (command->argv /* word [word](... */
3426 || dest->length /* word(... */
3427 || dest->nonnull /* ""(... */
3428 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003429 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003430 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3431 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003432 }
3433 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003434 endch = "}";
3435 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003436 endch = ")";
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003437 command->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003438 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003439 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003440 if (rcode == 0) {
3441 done_word(dest, &sub); /* finish off the final word in the subcontext */
3442 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003443 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003444 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003445 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003446 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003447 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003448}
3449
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003450/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003451 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003452static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003453{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003454 struct variable *var = get_local_var(src);
3455 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003456 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003457 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003458}
3459
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003460#if ENABLE_HUSH_TICK
3461/* Subroutines for copying $(...) and `...` things */
3462static void add_till_backquote(o_string *dest, struct in_str *input);
3463/* '...' */
3464static void add_till_single_quote(o_string *dest, struct in_str *input)
3465{
3466 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003467 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003468 if (ch == EOF)
3469 break;
3470 if (ch == '\'')
3471 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003472 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003473 }
3474}
3475/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3476static void add_till_double_quote(o_string *dest, struct in_str *input)
3477{
3478 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003479 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003480 if (ch == '"')
3481 break;
3482 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003483 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003484 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003485 }
3486 if (ch == EOF)
3487 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003488 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003489 if (ch == '`') {
3490 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003491 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003492 continue;
3493 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003494 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003495 }
3496}
3497/* Process `cmd` - copy contents until "`" is seen. Complicated by
3498 * \` quoting.
3499 * "Within the backquoted style of command substitution, backslash
3500 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3501 * The search for the matching backquote shall be satisfied by the first
3502 * backquote found without a preceding backslash; during this search,
3503 * if a non-escaped backquote is encountered within a shell comment,
3504 * a here-document, an embedded command substitution of the $(command)
3505 * form, or a quoted string, undefined results occur. A single-quoted
3506 * or double-quoted string that begins, but does not end, within the
3507 * "`...`" sequence produces undefined results."
3508 * Example Output
3509 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3510 */
3511static void add_till_backquote(o_string *dest, struct in_str *input)
3512{
3513 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003514 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003515 if (ch == '`')
3516 break;
3517 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003518 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003519 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003520 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003521 ch = ch2;
3522 }
3523 if (ch == EOF)
3524 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003525 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003526 }
3527}
3528/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3529 * quoting and nested ()s.
3530 * "With the $(command) style of command substitution, all characters
3531 * following the open parenthesis to the matching closing parenthesis
3532 * constitute the command. Any valid shell script can be used for command,
3533 * except a script consisting solely of redirections which produces
3534 * unspecified results."
3535 * Example Output
3536 * echo $(echo '(TEST)' BEST) (TEST) BEST
3537 * echo $(echo 'TEST)' BEST) TEST) BEST
3538 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3539 */
3540static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3541{
3542 int count = 0;
3543 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003544 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003545 if (ch == EOF)
3546 break;
3547 if (ch == '(')
3548 count++;
3549 if (ch == ')')
3550 if (--count < 0)
3551 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003552 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003553 if (ch == '\'') {
3554 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003555 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003556 continue;
3557 }
3558 if (ch == '"') {
3559 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003560 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003561 continue;
3562 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003563 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3564 ch = i_getch(input);
3565 if (ch == EOF)
3566 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003567 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003568 continue;
3569 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003570 }
3571}
3572#endif /* ENABLE_HUSH_TICK */
3573
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003574/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003575static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003576{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003577 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003578 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003579
3580 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003581 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003582 i_getch(input);
3583 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003584 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003585 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003586 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003587 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003588 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003589 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003590 if (!isalnum(ch) && ch != '_')
3591 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003592 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003593 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003594 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003595 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003596 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003597 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003598 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003599 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003600 o_addchr(dest, ch | quote_mask);
3601 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003602 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003603 case '$': /* pid */
3604 case '!': /* last bg pid */
3605 case '?': /* last exit code */
3606 case '#': /* number of args */
3607 case '*': /* args */
3608 case '@': /* args */
3609 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003610 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003611 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3612 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003613 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003614 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003615 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003616 if (ch == '}')
3617 break;
3618 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003619 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003620 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3621 return 1;
3622 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003623 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003624 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003625 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003626 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003627 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003628 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003629#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003630 case '(': {
3631 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003632 i_getch(input);
3633 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3634 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003635 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003636 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003637 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003638 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003639 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003640#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003641 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003642 i_getch(input);
3643 ch = i_peek(input);
3644 if (isalnum(ch)) { /* it's $_name or $_123 */
3645 ch = '_';
3646 goto make_var;
3647 }
3648 /* else: it's $_ */
3649 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003650 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003651 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003652 return 1;
3653 break;
3654 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003655 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003656 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003657 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003658 return 0;
3659}
3660
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003661/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003662 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3663 * Return code is 0 if end_trigger char is met,
3664 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003665 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003666static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003667 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003668{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003669 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003670 int redir_fd;
3671 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003672 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003673 int next;
3674
Denis Vlasenkoff097622007-10-01 10:00:45 +00003675 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003676 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003677 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003678
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003679 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 +00003680
Denis Vlasenko1a735862007-05-23 00:32:25 +00003681 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003682 m = CHAR_IFS;
3683 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003684 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003685 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003686 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003687 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003688 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003689 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003690 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003691 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003692 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003693 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003694 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003695 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003696 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003697 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003698 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3699 return 1;
3700 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003701 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003702 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3703 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003704 && ch == '='
3705 && is_assignment(dest->data)
3706 ) {
3707 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3708 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003709 continue;
3710 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003711 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003712 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003713 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003714 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003715 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003716 if (ch == EOF)
3717 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003718 /* If we aren't performing a substitution, treat
3719 * a newline as a command separator.
3720 * [why we don't handle it exactly like ';'? --vda] */
3721 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003722#if ENABLE_HUSH_CASE
3723 /* "case ... in <newline> word) ..." -
3724 * newlines are ignored (but ';' wouldn't be) */
3725 if (dest->length == 0 // && argv[0] == NULL
3726 && ctx->ctx_res_w == RES_MATCH
3727 ) {
3728 continue;
3729 }
3730#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003731 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003732 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003733 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003734 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003735 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003736 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003737 /* Special case: (...word) makes last word terminate,
3738 * as if ';' is seen */
3739 if (ch == ')') {
3740 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003741//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003742 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003743 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003744 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003745 if (!HAS_KEYWORDS
3746 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3747 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003748 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3749 return 0;
3750 }
3751 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003752 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003753 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003754 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003755
3756 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3757 /* ch is a special char and thus this word
3758 * cannot be an assignment: */
3759 dest->o_assignment = NOT_ASSIGNMENT;
3760 }
3761
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003762 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003763 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003764 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003765 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003766 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003767 if (ch == EOF || ch == '\n')
3768 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003769 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003770 }
Eric Andersen25f27032001-04-26 23:22:31 +00003771 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003772 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003773 }
3774 break;
3775 case '\\':
3776 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003777 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003778 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003779 return 1;
3780 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003781 /* bash:
3782 * "The backslash retains its special meaning [in "..."]
3783 * only when followed by one of the following characters:
3784 * $, `, ", \, or <newline>. A double quote may be quoted
3785 * within double quotes by preceding it with a backslash.
3786 * If enabled, history expansion will be performed unless
3787 * an ! appearing in double quotes is escaped using
3788 * a backslash. The backslash preceding the ! is not removed."
3789 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003790 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003791 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003792 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003793 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003794 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003795 }
3796 } else {
3797 o_addchr(dest, '\\');
3798 o_addchr(dest, i_getch(input));
3799 }
Eric Andersen25f27032001-04-26 23:22:31 +00003800 break;
3801 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003802 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003803 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3804 return 1;
3805 }
Eric Andersen25f27032001-04-26 23:22:31 +00003806 break;
3807 case '\'':
3808 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003809 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003810 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003811 if (ch == EOF) {
3812 syntax("unterminated '");
3813 debug_printf_parse("parse_stream return 1: unterminated '\n");
3814 return 1;
3815 }
3816 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003817 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003818 if (dest->o_assignment == NOT_ASSIGNMENT)
3819 o_addqchr(dest, ch);
3820 else
3821 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003822 }
Eric Andersen25f27032001-04-26 23:22:31 +00003823 break;
3824 case '"':
3825 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003826 shadow_quote ^= 1; /* invert */
3827 if (dest->o_assignment == NOT_ASSIGNMENT)
3828 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003829 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003830#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003831 case '`': {
3832 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003833 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003834 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003835 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003836 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003837 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003838 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003839 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003840#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003841 case '>':
3842 redir_fd = redirect_opt_num(dest);
3843 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003844 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003845 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003846 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003847 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003848 }
3849#if 0
3850 else if (next == '(') {
3851 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003852 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003853 return 1;
3854 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003855#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003856 setup_redirect(ctx, redir_fd, redir_style, input);
3857 break;
3858 case '<':
3859 redir_fd = redirect_opt_num(dest);
3860 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003861 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003862 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003863 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003864 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003865 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003866 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003867 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003868 }
3869#if 0
3870 else if (next == '(') {
3871 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003872 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003873 return 1;
3874 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003875#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003876 setup_redirect(ctx, redir_fd, redir_style, input);
3877 break;
3878 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003879#if ENABLE_HUSH_CASE
3880 case_semi:
3881#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003882 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003883 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003884#if ENABLE_HUSH_CASE
3885 /* Eat multiple semicolons, detect
3886 * whether it means something special */
3887 while (1) {
3888 ch = i_peek(input);
3889 if (ch != ';')
3890 break;
3891 i_getch(input);
3892 if (ctx->ctx_res_w == RES_CASEI) {
3893 ctx->ctx_dsemicolon = 1;
3894 ctx->ctx_res_w = RES_MATCH;
3895 break;
3896 }
3897 }
3898#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003899 new_cmd:
3900 /* We just finished a cmd. New one may start
3901 * with an assignment */
3902 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00003903 break;
3904 case '&':
3905 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003906 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003907 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003908 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003909 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003910 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003911 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003912 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00003913 case '|':
3914 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003915#if ENABLE_HUSH_CASE
3916 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00003917 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003918#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003919 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003920 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003921 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003922 } else {
3923 /* we could pick up a file descriptor choice here
3924 * with redirect_opt_num(), but bash doesn't do it.
3925 * "echo foo 2| cat" yields "foo 2". */
3926 done_command(ctx);
3927 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003928 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00003929 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003930#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00003931 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003932 if (dest->length == 0 /* not word(... */
3933 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003934 && ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003935 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003936 ) {
3937 continue;
3938 }
3939#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003940#if 0 /* TODO: implement functions */
3941 if (dest->length != 0 /* not just () but word() */
3942 && dest->nonnull == 0 /* not a"b"c() */
3943 && ctx->command->argv == NULL /* it's the first word */
3944 && i_peek(input) == ')'
3945 ) {
3946 bb_error_msg("seems like a function definition");
3947 if (match_reserved_word(dest))
3948 bb_error_msg("but '%s' is a reserved word!", dest->data);
3949 }
3950#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003951 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003952 if (parse_group(dest, ctx, input, ch) != 0) {
3953 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003954 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003955 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003956 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00003957 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003958#if ENABLE_HUSH_CASE
3959 if (ctx->ctx_res_w == RES_MATCH)
3960 goto case_semi;
3961#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003962 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003963 /* proper use of this character is caught by end_trigger:
3964 * if we see {, we call parse_group(..., end_trigger='}')
3965 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003966 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003967 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003968 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003969 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003970 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003971 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003972 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003973 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003974 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003975 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003976 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003977 return 0;
3978}
3979
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003980static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003981{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003982 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003983 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003984}
3985
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003986static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003987{
Denis Vlasenko87a86552008-07-29 19:43:10 +00003988 G.ifs = getenv("IFS");
3989 if (G.ifs == NULL)
3990 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003991 /* Precompute a list of 'flow through' behavior so it can be treated
3992 * quickly up front. Computation is necessary because of IFS.
3993 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003994 * The charmap[] array only really needs two bits each,
3995 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003996 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003997 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003998#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003999 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004000#else
4001 set_in_charmap("\\$\"", CHAR_SPECIAL);
4002#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004003 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004004 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004005}
4006
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004007/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004008 * from builtin_source() and builtin_eval() */
4009static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004010{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004011 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004012 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004013 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004014
Eric Andersen25f27032001-04-26 23:22:31 +00004015 do {
4016 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004017 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004018#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004019 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004020#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004021 /* We will stop & execute after each ';' or '\n'.
4022 * Example: "sleep 9999; echo TEST" + ctrl-C:
4023 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004024 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004025 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004026#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004027 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004028 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004029 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004030#endif
4031 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004032 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004033 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004034 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004035 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4036 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004037 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004038 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004039#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004040 if (ctx.old_flag != 0) {
4041 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004042 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004043 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004044#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004045 /*temp.nonnull = 0; - o_free does it below */
4046 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004047 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004048 /* Discard all unprocessed line input, force prompt on */
4049 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004050#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004051 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004052#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004053 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004054 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004055 /* loop on syntax errors, return on EOF: */
4056 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004057 return 0;
4058}
4059
Denis Vlasenko170435c2007-05-23 13:01:10 +00004060static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004061{
4062 struct in_str input;
4063 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004064 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004065}
4066
Denis Vlasenko170435c2007-05-23 13:01:10 +00004067static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004068{
4069 int rcode;
4070 struct in_str input;
4071 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004072 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004073 return rcode;
4074}
4075
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004076#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004077/* Make sure we have a controlling tty. If we get started under a job
4078 * aware app (like bash for example), make sure we are now in charge so
4079 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004080static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004081{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004082 pid_t shell_pgrp;
4083
Denis Vlasenko87a86552008-07-29 19:43:10 +00004084 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004085 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004086
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004087 /* If we were ran as 'hush &',
4088 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004089 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004090 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004091 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004092 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004093 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004094
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004095 /* Ignore job-control and misc signals. */
4096 set_jobctrl_sighandler(SIG_IGN);
4097 set_misc_sighandler(SIG_IGN);
4098//huh? signal(SIGCHLD, SIG_IGN);
4099
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004100 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004101 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004102
4103 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004104 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004105 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004106 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004107}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004108#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004109
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004110
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004111int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004112int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004113{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004114 static const struct variable const_shell_ver = {
4115 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004116 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004117 .max_len = 1, /* 0 can provoke free(name) */
4118 .flg_export = 1,
4119 .flg_read_only = 1,
4120 };
4121
Eric Andersen25f27032001-04-26 23:22:31 +00004122 int opt;
4123 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004124 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004125 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004126
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004127 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004128
Denis Vlasenko87a86552008-07-29 19:43:10 +00004129 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004130
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004131 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004132 G.shell_ver = const_shell_ver; /* copying struct here */
4133 G.top_var = &G.shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004134 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4135 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004136 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004137 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004138 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004139 if (e) while (*e) {
4140 char *value = strchr(*e, '=');
4141 if (value) { /* paranoia */
4142 cur_var->next = xzalloc(sizeof(*cur_var));
4143 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004144 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004145 cur_var->max_len = strlen(*e);
4146 cur_var->flg_export = 1;
4147 }
4148 e++;
4149 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004150 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004151
Denis Vlasenko38f63192007-01-22 09:03:07 +00004152#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004153 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004154#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004155 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004156 G.global_argc = argc;
4157 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004158 /* Initialize some more globals to non-zero values */
4159 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004160#if ENABLE_HUSH_INTERACTIVE
4161#if ENABLE_FEATURE_EDITING
4162 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004163#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004164 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004165#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004166
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004167 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004168 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004169
4170 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004171 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004172 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004173 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004174 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004175 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004176 fclose(input);
4177 }
Eric Andersen25f27032001-04-26 23:22:31 +00004178 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004179 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004180
Eric Andersen25f27032001-04-26 23:22:31 +00004181 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4182 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004183 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004184 G.global_argv = argv + optind;
4185 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004186 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004187 goto final_return;
4188 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004189 /* Well, we cannot just declare interactiveness,
4190 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004191 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004192 break;
4193 case 'f':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004194 G.fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004195 break;
4196 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004197#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004198 fprintf(stderr, "Usage: sh [FILE]...\n"
4199 " or: sh -c command [args]...\n\n");
4200 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004201#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004202 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004203#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004204 }
4205 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004206#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004207 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004208 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004209 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004210 * no arguments remaining or the -s flag given
4211 * standard input is a terminal
4212 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004213 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004214 if (argv[optind] == NULL && input == stdin
4215 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4216 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004217 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4218 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4219 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004220 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004221 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4222 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004223 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004224 G.interactive_fd = dup(STDIN_FILENO);
4225 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004226 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004227 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004228 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004229 // TODO: track & disallow any attempts of user
4230 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004231 }
Eric Andersen25f27032001-04-26 23:22:31 +00004232 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004233 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4234 if (G.interactive_fd) {
4235 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004236 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004237 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004238 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004239 * (we reset die_sleep = 0 whereever we [v]fork) */
4240 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004241 if (setjmp(die_jmp)) {
4242 /* xfunc has failed! die die die */
4243 hush_exit(xfunc_error_retval);
4244 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004245#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00004246 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004247 printf("Enter 'help' for a list of built-in commands.\n\n");
4248#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004249 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004250#elif ENABLE_HUSH_INTERACTIVE
4251/* no job control compiled, only prompt/line editing */
4252 if (argv[optind] == NULL && input == stdin
4253 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4254 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004255 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4256 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004257 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004258 G.interactive_fd = dup(STDIN_FILENO);
4259 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004260 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004261 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004262 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004263 if (G.interactive_fd) {
4264 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004265 set_misc_sighandler(SIG_IGN);
4266 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004267 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004268#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004269
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004270 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004271 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004272 } else {
4273 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004274 G.global_argv = argv + optind;
4275 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004276 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004277 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004278 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004279 }
Eric Andersen25f27032001-04-26 23:22:31 +00004280
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004281 final_return:
4282
Denis Vlasenko38f63192007-01-22 09:03:07 +00004283#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004284 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004285 if (G.cwd != bb_msg_unknown)
4286 free((char*)G.cwd);
4287 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004288 while (cur_var) {
4289 struct variable *tmp = cur_var;
4290 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004291 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004292 cur_var = cur_var->next;
4293 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004294 }
Eric Andersen25f27032001-04-26 23:22:31 +00004295#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004296 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004297}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004298
4299
4300#if ENABLE_LASH
4301int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4302int lash_main(int argc, char **argv)
4303{
4304 //bb_error_msg("lash is deprecated, please use hush instead");
4305 return hush_main(argc, argv);
4306}
4307#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004308
4309
4310/*
4311 * Built-ins
4312 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004313static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004314{
4315 return 0;
4316}
4317
4318static int builtin_test(char **argv)
4319{
4320 int argc = 0;
4321 while (*argv) {
4322 argc++;
4323 argv++;
4324 }
4325 return test_main(argc, argv - argc);
4326}
4327
4328static int builtin_echo(char **argv)
4329{
4330 int argc = 0;
4331 while (*argv) {
4332 argc++;
4333 argv++;
4334 }
4335 return echo_main(argc, argv - argc);
4336}
4337
4338static int builtin_eval(char **argv)
4339{
4340 int rcode = EXIT_SUCCESS;
4341
4342 if (argv[1]) {
4343 char *str = expand_strvec_to_string(argv + 1);
4344 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4345 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004346 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004347 }
4348 return rcode;
4349}
4350
4351static int builtin_cd(char **argv)
4352{
4353 const char *newdir;
4354 if (argv[1] == NULL) {
4355 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4356 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4357 newdir = getenv("HOME") ? : "/";
4358 } else
4359 newdir = argv[1];
4360 if (chdir(newdir)) {
4361 printf("cd: %s: %s\n", newdir, strerror(errno));
4362 return EXIT_FAILURE;
4363 }
4364 set_cwd();
4365 return EXIT_SUCCESS;
4366}
4367
4368static int builtin_exec(char **argv)
4369{
4370 if (argv[1] == NULL)
4371 return EXIT_SUCCESS; /* bash does this */
4372 {
4373#if !BB_MMU
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004374 char **ptrs2free = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004375#endif
4376// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004377 pseudo_exec_argv(&ptrs2free, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004378 /* never returns */
4379 }
4380}
4381
4382static int builtin_exit(char **argv)
4383{
4384// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4385 //puts("exit"); /* bash does it */
4386// TODO: warn if we have background jobs: "There are stopped jobs"
4387// On second consecutive 'exit', exit anyway.
4388 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004389 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004390 /* mimic bash: exit 123abc == exit 255 + error msg */
4391 xfunc_error_retval = 255;
4392 /* bash: exit -2 == exit 254, no error msg */
4393 hush_exit(xatoi(argv[1]) & 0xff);
4394}
4395
4396static int builtin_export(char **argv)
4397{
4398 const char *value;
4399 char *name = argv[1];
4400
4401 if (name == NULL) {
4402 // TODO:
4403 // ash emits: export VAR='VAL'
4404 // bash: declare -x VAR="VAL"
4405 // (both also escape as needed (quotes, $, etc))
4406 char **e = environ;
4407 if (e)
4408 while (*e)
4409 puts(*e++);
4410 return EXIT_SUCCESS;
4411 }
4412
4413 value = strchr(name, '=');
4414 if (!value) {
4415 /* They are exporting something without a =VALUE */
4416 struct variable *var;
4417
4418 var = get_local_var(name);
4419 if (var) {
4420 var->flg_export = 1;
4421 putenv(var->varstr);
4422 }
4423 /* bash does not return an error when trying to export
4424 * an undefined variable. Do likewise. */
4425 return EXIT_SUCCESS;
4426 }
4427
4428 set_local_var(xstrdup(name), 1);
4429 return EXIT_SUCCESS;
4430}
4431
4432#if ENABLE_HUSH_JOB
4433/* built-in 'fg' and 'bg' handler */
4434static int builtin_fg_bg(char **argv)
4435{
4436 int i, jobnum;
4437 struct pipe *pi;
4438
Denis Vlasenko87a86552008-07-29 19:43:10 +00004439 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004440 return EXIT_FAILURE;
4441 /* If they gave us no args, assume they want the last backgrounded task */
4442 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004443 for (pi = G.job_list; pi; pi = pi->next) {
4444 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004445 goto found;
4446 }
4447 }
4448 bb_error_msg("%s: no current job", argv[0]);
4449 return EXIT_FAILURE;
4450 }
4451 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4452 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4453 return EXIT_FAILURE;
4454 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004455 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004456 if (pi->jobid == jobnum) {
4457 goto found;
4458 }
4459 }
4460 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4461 return EXIT_FAILURE;
4462 found:
4463 // TODO: bash prints a string representation
4464 // of job being foregrounded (like "sleep 1 | cat")
4465 if (*argv[0] == 'f') {
4466 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004467 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004468 }
4469
4470 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004471 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4472 for (i = 0; i < pi->num_cmds; i++) {
4473 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4474 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004475 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004476 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004477
4478 i = kill(- pi->pgrp, SIGCONT);
4479 if (i < 0) {
4480 if (errno == ESRCH) {
4481 delete_finished_bg_job(pi);
4482 return EXIT_SUCCESS;
4483 } else {
4484 bb_perror_msg("kill (SIGCONT)");
4485 }
4486 }
4487
4488 if (*argv[0] == 'f') {
4489 remove_bg_job(pi);
4490 return checkjobs_and_fg_shell(pi);
4491 }
4492 return EXIT_SUCCESS;
4493}
4494#endif
4495
4496#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004497static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004498{
4499 const struct built_in_command *x;
4500
4501 printf("\nBuilt-in commands:\n");
4502 printf("-------------------\n");
4503 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4504 printf("%s\t%s\n", x->cmd, x->descr);
4505 }
4506 printf("\n\n");
4507 return EXIT_SUCCESS;
4508}
4509#endif
4510
4511#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004512static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004513{
4514 struct pipe *job;
4515 const char *status_string;
4516
Denis Vlasenko87a86552008-07-29 19:43:10 +00004517 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004518 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004519 status_string = "Stopped";
4520 else
4521 status_string = "Running";
4522
4523 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4524 }
4525 return EXIT_SUCCESS;
4526}
4527#endif
4528
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004529static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004530{
4531 puts(set_cwd());
4532 return EXIT_SUCCESS;
4533}
4534
4535static int builtin_read(char **argv)
4536{
4537 char *string;
4538 const char *name = argv[1] ? argv[1] : "REPLY";
4539
4540 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4541 return set_local_var(string, 0);
4542}
4543
4544/* built-in 'set [VAR=value]' handler */
4545static int builtin_set(char **argv)
4546{
4547 char *temp = argv[1];
4548 struct variable *e;
4549
4550 if (temp == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004551 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004552 puts(e->varstr);
4553 else
4554 set_local_var(xstrdup(temp), 0);
4555
4556 return EXIT_SUCCESS;
4557}
4558
4559static int builtin_shift(char **argv)
4560{
4561 int n = 1;
4562 if (argv[1]) {
4563 n = atoi(argv[1]);
4564 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004565 if (n >= 0 && n < G.global_argc) {
4566 G.global_argv[n] = G.global_argv[0];
4567 G.global_argc -= n;
4568 G.global_argv += n;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004569 return EXIT_SUCCESS;
4570 }
4571 return EXIT_FAILURE;
4572}
4573
4574static int builtin_source(char **argv)
4575{
4576 FILE *input;
4577 int status;
4578
4579 if (argv[1] == NULL)
4580 return EXIT_FAILURE;
4581
4582 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004583 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004584 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004585 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004586 return EXIT_FAILURE;
4587 }
4588 close_on_exec_on(fileno(input));
4589
4590 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004591 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004592 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00004593 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004594 status = parse_and_run_file(input);
4595 fclose(input);
4596 return status;
4597}
4598
4599static int builtin_umask(char **argv)
4600{
4601 mode_t new_umask;
4602 const char *arg = argv[1];
4603 char *end;
4604 if (arg) {
4605 new_umask = strtoul(arg, &end, 8);
4606 if (*end != '\0' || end == arg) {
4607 return EXIT_FAILURE;
4608 }
4609 } else {
4610 new_umask = umask(0);
4611 printf("%.3o\n", (unsigned) new_umask);
4612 }
4613 umask(new_umask);
4614 return EXIT_SUCCESS;
4615}
4616
4617static int builtin_unset(char **argv)
4618{
4619 /* bash always returns true */
4620 unset_local_var(argv[1]);
4621 return EXIT_SUCCESS;
4622}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004623
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004624#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004625static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004626{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004627 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004628 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004629 return EXIT_SUCCESS; /* bash compat */
4630 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004631 G.flag_break_continue++; /* BC_BREAK = 1 */
4632 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004633 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004634 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4635 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004636 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004637 G.flag_break_continue = BC_BREAK;
4638 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004639 }
4640 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004641 if (G.depth_of_loop < G.depth_break_continue)
4642 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004643 return EXIT_SUCCESS;
4644}
4645
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004646static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004647{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004648 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4649 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004650}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004651#endif