blob: 67e689fe2ed1f948597f9e80ea45aef0a284a3f5 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Denis Vlasenkoa8442002008-06-14 11:00:17 +000023 * o_addchr() derived from similar w_addchar function in glibc-2.2.
Eric Andersen25f27032001-04-26 23:22:31 +000024 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko424f79b2009-03-22 14:23:34 +000025 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000027 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
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 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000059 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000060 * propagate syntax errors, die on resource errors?
61 * continuation lines, both explicit and implicit - done?
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000062 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000063 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000064 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000065 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000066
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000067#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenko424f79b2009-03-22 14:23:34 +000068//TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
Denis Vlasenko61befda2008-11-25 01:36:03 +000069//#include "applet_tables.h" doesn't work
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 Vlasenko424f79b2009-03-22 14:23:34 +000076#define HUSH_VER_STR "0.92"
Denis Vlasenkod01ff132007-05-02 21:40:23 +000077
Denis Vlasenko61befda2008-11-25 01:36:03 +000078#if defined SINGLE_APPLET_MAIN
79/* STANDALONE does not make sense, and won't compile */
80#undef CONFIG_FEATURE_SH_STANDALONE
81#undef ENABLE_FEATURE_SH_STANDALONE
82#undef USE_FEATURE_SH_STANDALONE
83#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
84#define ENABLE_FEATURE_SH_STANDALONE 0
85#define USE_FEATURE_SH_STANDALONE(...)
86#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87#endif
88
Denis Vlasenko05743d72008-02-10 12:10:08 +000089#if !BB_MMU && ENABLE_HUSH_TICK
90//#undef ENABLE_HUSH_TICK
91//#define ENABLE_HUSH_TICK 0
92#warning On NOMMU, hush command substitution is dangerous.
93#warning Dont use it for commands which produce lots of output.
94#warning For more info see shell/hush.c, generate_stream_from_list().
95#endif
96
Denis Vlasenko05743d72008-02-10 12:10:08 +000097#if !ENABLE_HUSH_INTERACTIVE
98#undef ENABLE_FEATURE_EDITING
99#define ENABLE_FEATURE_EDITING 0
100#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
101#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000102#endif
103
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000104/* Do we support ANY keywords? */
105#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
106#define HAS_KEYWORDS 1
107#define IF_HAS_KEYWORDS(...) __VA_ARGS__
108#define IF_HAS_NO_KEYWORDS(...)
109#else
110#define HAS_KEYWORDS 0
111#define IF_HAS_KEYWORDS(...)
112#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
113#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000114
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000115/* Keep unconditionally on for now */
116#define HUSH_DEBUG 1
117/* In progress... */
118#define ENABLE_HUSH_FUNCTIONS 0
119
120
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000121/* If you comment out one of these below, it will be #defined later
122 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000123#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000124/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000125#define debug_printf_parse(...) do {} while (0)
126#define debug_print_tree(a, b) do {} while (0)
127#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000128#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000129#define debug_printf_jobs(...) do {} while (0)
130#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000131#define debug_printf_glob(...) do {} while (0)
132#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000133#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000134#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000135
136#ifndef debug_printf
137#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000138#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000139
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000140#ifndef debug_printf_parse
141#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000142#endif
143
144#ifndef debug_printf_exec
145#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
146#endif
147
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000148#ifndef debug_printf_env
149#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
150#endif
151
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000152#ifndef debug_printf_jobs
153#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000154#define DEBUG_JOBS 1
155#else
156#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000157#endif
158
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000159#ifndef debug_printf_expand
160#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
161#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000162#else
163#define DEBUG_EXPAND 0
164#endif
165
166#ifndef debug_printf_glob
167#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
168#define DEBUG_GLOB 1
169#else
170#define DEBUG_GLOB 0
171#endif
172
173#ifndef debug_printf_list
174#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000175#endif
176
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000177#ifndef debug_printf_subst
178#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
179#endif
180
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000181#ifndef debug_printf_clean
182/* broken, of course, but OK for testing */
183static const char *indenter(int i)
184{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000185 static const char blanks[] ALIGN1 =
186 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000187 return &blanks[sizeof(blanks) - i - 1];
188}
189#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000190#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000191#endif
192
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000193#if DEBUG_EXPAND
194static void debug_print_strings(const char *prefix, char **vv)
195{
196 fprintf(stderr, "%s:\n", prefix);
197 while (*vv)
198 fprintf(stderr, " '%s'\n", *vv++);
199}
200#else
201#define debug_print_strings(prefix, vv) ((void)0)
202#endif
203
Denis Vlasenkof962a032007-11-23 12:50:54 +0000204/*
205 * Leak hunting. Use hush_leaktool.sh for post-processing.
206 */
207#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000208/* suppress "warning: no previous prototype..." */
209void *xxmalloc(int lineno, size_t size);
210void *xxrealloc(int lineno, void *ptr, size_t size);
211char *xxstrdup(int lineno, const char *str);
212void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000213void *xxmalloc(int lineno, size_t size)
214{
215 void *ptr = xmalloc((size + 0xff) & ~0xff);
216 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
217 return ptr;
218}
219void *xxrealloc(int lineno, void *ptr, size_t size)
220{
221 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
222 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
223 return ptr;
224}
225char *xxstrdup(int lineno, const char *str)
226{
227 char *ptr = xstrdup(str);
228 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
229 return ptr;
230}
231void xxfree(void *ptr)
232{
233 fprintf(stderr, "free %p\n", ptr);
234 free(ptr);
235}
236#define xmalloc(s) xxmalloc(__LINE__, s)
237#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
238#define xstrdup(s) xxstrdup(__LINE__, s)
239#define free(p) xxfree(p)
240#endif
241
242
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000243static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000244
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000245#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000246
Denis Vlasenko5703c222008-06-15 11:49:42 +0000247#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000248#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000249
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000250typedef enum redir_type {
Eric Andersen25f27032001-04-26 23:22:31 +0000251 REDIRECT_INPUT = 1,
252 REDIRECT_OVERWRITE = 2,
253 REDIRECT_APPEND = 3,
254 REDIRECT_HEREIS = 4,
255 REDIRECT_IO = 5
256} redir_type;
257
Denis Vlasenko55789c62008-06-18 16:30:42 +0000258/* The descrip member of this structure is only used to make
259 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000260static const struct {
261 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000262 signed char default_fd;
263 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000264} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000265 { 0, 0, "()" },
266 { O_RDONLY, 0, "<" },
267 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
268 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
269 { O_RDONLY, -1, "<<" },
270 { O_RDWR, 1, "<>" }
271};
272
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000273typedef enum pipe_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000274 PIPE_SEQ = 1,
275 PIPE_AND = 2,
276 PIPE_OR = 3,
277 PIPE_BG = 4,
278} pipe_style;
279
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000280typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000281 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000282#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000283 RES_IF ,
284 RES_THEN ,
285 RES_ELIF ,
286 RES_ELSE ,
287 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000288#endif
289#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000290 RES_FOR ,
291 RES_WHILE ,
292 RES_UNTIL ,
293 RES_DO ,
294 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000295#endif
296#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000297 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000298#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000299#if ENABLE_HUSH_CASE
300 RES_CASE ,
301 /* two pseudo-keywords support contrived "case" syntax: */
302 RES_MATCH , /* "word)" */
303 RES_CASEI , /* "this command is inside CASE" */
304 RES_ESAC ,
305#endif
306 RES_XXXX ,
307 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000308} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000309
Eric Andersen25f27032001-04-26 23:22:31 +0000310struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000311 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000312 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000313 int fd; /* file descriptor being redirected */
314 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000315 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000316};
317
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000318struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000319 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000320 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000321 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000322 smallint grp_type; /* GRP_xxx */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000323 struct pipe *group; /* if non-NULL, this "prog" is {} group,
324 * subshell, or a compound statement */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000325 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000326 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000327};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000328/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
329 * and on execution these are substituted with their values.
330 * Substitution can make _several_ words out of one argv[n]!
331 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000332 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000333 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000334#define GRP_NORMAL 0
335#define GRP_SUBSHELL 1
336#if ENABLE_HUSH_FUNCTIONS
337#define GRP_FUNCTION 2
338#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000339
340struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000341 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000342 int num_cmds; /* total number of commands in job */
343 int alive_cmds; /* number of commands running (not exited) */
344 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000345#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000346 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000347 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000348 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000349#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000350 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000351 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000352 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
353 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000354};
355
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000356/* This holds pointers to the various results of parsing */
357struct parse_context {
358 struct command *command;
359 struct pipe *list_head;
360 struct pipe *pipe;
361 struct redir_struct *pending_redirect;
362#if HAS_KEYWORDS
363 smallint ctx_res_w;
364 smallint ctx_inverted; /* "! cmd | cmd" */
365#if ENABLE_HUSH_CASE
366 smallint ctx_dsemicolon; /* ";;" seen */
367#endif
368 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
369 struct parse_context *stack;
370#endif
371};
372
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000373/* On program start, environ points to initial environment.
374 * putenv adds new pointers into it, unsetenv removes them.
375 * Neither of these (de)allocates the strings.
376 * setenv allocates new strings in malloc space and does putenv,
377 * and thus setenv is unusable (leaky) for shell's purposes */
378#define setenv(...) setenv_is_leaky_dont_use()
379struct variable {
380 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000381 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000382 int max_len; /* if > 0, name is part of initial env; else name is malloced */
383 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000384 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000385};
386
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000387typedef struct o_string {
Eric Andersen25f27032001-04-26 23:22:31 +0000388 char *data;
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000389 int length; /* position where data is appended */
Eric Andersen25f27032001-04-26 23:22:31 +0000390 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000391 /* Misnomer! it's not "quoting", it's "protection against globbing"!
392 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000393 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000394 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000395 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000396 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000397 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000398} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000399enum {
400 MAYBE_ASSIGNMENT = 0,
401 DEFINITELY_ASSIGNMENT = 1,
402 NOT_ASSIGNMENT = 2,
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000403 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000404};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000405/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000406#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000407
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000408/* I can almost use ordinary FILE*. Is open_memstream() universally
Eric Andersen25f27032001-04-26 23:22:31 +0000409 * available? Where is it documented? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000410typedef struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000411 const char *p;
412 /* eof_flag=1: last char in ->p is really an EOF */
413 char eof_flag; /* meaningless if ->p == NULL */
414 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000415#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000416 smallint promptme;
417 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000418#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000419 FILE *file;
420 int (*get) (struct in_str *);
421 int (*peek) (struct in_str *);
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000422} in_str;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000423#define i_getch(input) ((input)->get(input))
424#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000425
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000426enum {
427 CHAR_ORDINARY = 0,
428 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
429 CHAR_IFS = 2, /* treated as ordinary if quoted */
430 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000431};
432
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000433enum {
434 BC_BREAK = 1,
435 BC_CONTINUE = 2,
436};
437
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000438
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000439/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000440/* Sorted roughly by size (smaller offsets == smaller code) */
441struct globals {
442#if ENABLE_HUSH_INTERACTIVE
443 /* 'interactive_fd' is a fd# open to ctty, if we have one
444 * _AND_ if we decided to act interactively */
445 int interactive_fd;
446 const char *PS1;
447 const char *PS2;
448#endif
449#if ENABLE_FEATURE_EDITING
450 line_input_t *line_input_state;
451#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000452 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000453 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000454#if ENABLE_HUSH_JOB
455 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000456 pid_t saved_tty_pgrp;
457 int last_jobid;
458 struct pipe *job_list;
459 struct pipe *toplevel_list;
460 smallint ctrl_z_flag;
461#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000462#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000463 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000464#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000465 smallint fake_mode;
466 /* these three support $?, $#, and $1 */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +0000467 smalluint last_return_code;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000468 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000469 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000470 /* how many non-NULL argv's we have. NB: $# + 1 */
471 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000472 char **global_argv;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000473#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000474 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000475 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000476#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000477 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000478 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000479 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000480 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000481#if ENABLE_FEATURE_SH_STANDALONE
482 struct nofork_save_area nofork_save;
483#endif
484#if ENABLE_HUSH_JOB
485 sigjmp_buf toplevel_jb;
486#endif
487 unsigned char charmap[256];
488 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
489};
490
491#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000492/* Not #defining name to G.name - this quickly gets unwieldy
493 * (too many defines). Also, I actually prefer to see when a variable
494 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000495#define INIT_G() do { \
496 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
497} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000498
499
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000500/* Function prototypes for builtins */
501static int builtin_cd(char **argv);
502static int builtin_echo(char **argv);
503static int builtin_eval(char **argv);
504static int builtin_exec(char **argv);
505static int builtin_exit(char **argv);
506static int builtin_export(char **argv);
507#if ENABLE_HUSH_JOB
508static int builtin_fg_bg(char **argv);
509static int builtin_jobs(char **argv);
510#endif
511#if ENABLE_HUSH_HELP
512static int builtin_help(char **argv);
513#endif
514static int builtin_pwd(char **argv);
515static int builtin_read(char **argv);
516static int builtin_test(char **argv);
517static int builtin_true(char **argv);
518static int builtin_set(char **argv);
519static int builtin_shift(char **argv);
520static int builtin_source(char **argv);
521static int builtin_umask(char **argv);
522static int builtin_unset(char **argv);
523#if ENABLE_HUSH_LOOPS
524static int builtin_break(char **argv);
525static int builtin_continue(char **argv);
526#endif
527//static int builtin_not_written(char **argv);
528
529/* Table of built-in functions. They can be forked or not, depending on
530 * context: within pipes, they fork. As simple commands, they do not.
531 * When used in non-forking context, they can change global variables
532 * in the parent shell process. If forked, of course they cannot.
533 * For example, 'unset foo | whatever' will parse and run, but foo will
534 * still be set at the end. */
535struct built_in_command {
536 const char *cmd;
537 int (*function)(char **argv);
538#if ENABLE_HUSH_HELP
539 const char *descr;
540#define BLTIN(cmd, func, help) { cmd, func, help }
541#else
542#define BLTIN(cmd, func, help) { cmd, func }
543#endif
544};
545
546/* For now, echo and test are unconditionally enabled.
547 * Maybe make it configurable? */
548static const struct built_in_command bltins[] = {
549 BLTIN("." , builtin_source, "Run commands in a file"),
550 BLTIN(":" , builtin_true, "No-op"),
551 BLTIN("[" , builtin_test, "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000552#if ENABLE_HUSH_JOB
553 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
554#endif
555#if ENABLE_HUSH_LOOPS
556 BLTIN("break" , builtin_break, "Exit from a loop"),
557#endif
558 BLTIN("cd" , builtin_cd, "Change directory"),
559#if ENABLE_HUSH_LOOPS
560 BLTIN("continue", builtin_continue, "Start new loop iteration"),
561#endif
562 BLTIN("echo" , builtin_echo, "Write to stdout"),
563 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
564 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
565 BLTIN("exit" , builtin_exit, "Exit"),
566 BLTIN("export", builtin_export, "Set environment variable"),
567#if ENABLE_HUSH_JOB
568 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
569 BLTIN("jobs" , builtin_jobs, "List active jobs"),
570#endif
571 BLTIN("pwd" , builtin_pwd, "Print current directory"),
572 BLTIN("read" , builtin_read, "Input environment variable"),
573// BLTIN("return", builtin_not_written, "Return from a function"),
574 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
575 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
576// BLTIN("trap" , builtin_not_written, "Trap signals"),
577 BLTIN("test" , builtin_test, "Test condition"),
578// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
579 BLTIN("umask" , builtin_umask, "Set file creation mask"),
580 BLTIN("unset" , builtin_unset, "Unset environment variable"),
581#if ENABLE_HUSH_HELP
582 BLTIN("help" , builtin_help, "List shell built-in commands"),
583#endif
584};
585
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000586
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000587#if 1
588/* Normal */
589static void syntax(const char *msg)
590{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000591#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000592 /* Was using fancy stuff:
Denis Vlasenko87a86552008-07-29 19:43:10 +0000593 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000594 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000595 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000596 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000597 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000598#else
599 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
600#endif
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000601}
602#else
603/* Debug */
604static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000605{
Denis Vlasenko87a86552008-07-29 19:43:10 +0000606#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoff182a32008-07-05 20:29:59 +0000607 void FAST_FUNC (*fp)(const char *s, ...);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000608 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000609 fp("syntax error hush.c:%d", line);
Denis Vlasenko87a86552008-07-29 19:43:10 +0000610#else
611 bb_error_msg_and_die("syntax error hush.c:%d", line);
612#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000613}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000614#define syntax(str) syntax_lineno(__LINE__)
615#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000616
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000617static int glob_needed(const char *s)
618{
619 while (*s) {
620 if (*s == '\\')
621 s++;
622 if (*s == '*' || *s == '[' || *s == '?')
623 return 1;
624 s++;
625 }
626 return 0;
627}
628
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000629static int is_assignment(const char *s)
630{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000631 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000632 return 0;
633 s++;
634 while (isalnum(*s) || *s == '_')
635 s++;
636 return *s == '=';
637}
638
Denis Vlasenko55789c62008-06-18 16:30:42 +0000639/* Replace each \x with x in place, return ptr past NUL. */
640static char *unbackslash(char *src)
641{
642 char *dst = src;
643 while (1) {
644 if (*src == '\\')
645 src++;
646 if ((*dst++ = *src++) == '\0')
647 break;
648 }
649 return dst;
650}
651
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000652static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000653{
654 int i;
655 unsigned count1;
656 unsigned count2;
657 char **v;
658
659 v = strings;
660 count1 = 0;
661 if (v) {
662 while (*v) {
663 count1++;
664 v++;
665 }
666 }
667 count2 = 0;
668 v = add;
669 while (*v) {
670 count2++;
671 v++;
672 }
673 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
674 v[count1 + count2] = NULL;
675 i = count2;
676 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000677 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000678 return v;
679}
680
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000681static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000682{
683 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000684 v[0] = add;
685 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000686 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000687}
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000688
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000689static void putenv_all(char **strings)
690{
691 if (!strings)
692 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000693 while (*strings) {
694 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000695 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000696 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000697}
698
699static char **putenv_all_and_save_old(char **strings)
700{
701 char **old = NULL;
702 char **s = strings;
703
704 if (!strings)
705 return old;
706 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000707 char *v, *eq;
708
709 eq = strchr(*strings, '=');
710 if (eq) {
711 *eq = '\0';
712 v = getenv(*strings);
713 *eq = '=';
714 if (v) {
715 /* v points to VAL in VAR=VAL, go back to VAR */
716 v -= (eq - *strings) + 1;
717 old = add_string_to_strings(old, v);
718 }
719 }
720 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000721 }
722 putenv_all(s);
723 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000724}
725
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000726static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000727{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000728 char **v;
729
730 if (!strings)
731 return;
732
733 v = strings;
734 while (*v) {
735 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000736 debug_printf_env("unsetenv '%s'\n", *v);
737 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000738 }
739 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000740 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000741 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000742}
743
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000744static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000745{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000746 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000747}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000748
749
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000750/* Signals are grouped, we handle them in batches */
751static void set_misc_sighandler(void (*handler)(int))
752{
753 bb_signals(0
754 + (1 << SIGINT)
755 + (1 << SIGQUIT)
756 + (1 << SIGTERM)
757 , handler);
758}
759
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000760#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000761
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000762static void set_fatal_sighandler(void (*handler)(int))
763{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000764 bb_signals(0
765 + (1 << SIGILL)
766 + (1 << SIGTRAP)
767 + (1 << SIGABRT)
768 + (1 << SIGFPE)
769 + (1 << SIGBUS)
770 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000771 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000772 + (1 << SIGHUP)
773 + (1 << SIGPIPE)
774 + (1 << SIGALRM)
775 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000776}
777static void set_jobctrl_sighandler(void (*handler)(int))
778{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000779 bb_signals(0
780 + (1 << SIGTSTP)
781 + (1 << SIGTTIN)
782 + (1 << SIGTTOU)
783 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000784}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000785/* SIGCHLD is special and handled separately */
786
787static void set_every_sighandler(void (*handler)(int))
788{
789 set_fatal_sighandler(handler);
790 set_jobctrl_sighandler(handler);
791 set_misc_sighandler(handler);
792 signal(SIGCHLD, handler);
793}
794
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000795static void handler_ctrl_c(int sig UNUSED_PARAM)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000796{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000797 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000798// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenko87a86552008-07-29 19:43:10 +0000799 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000800}
801
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000802static void handler_ctrl_z(int sig UNUSED_PARAM)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000803{
804 pid_t pid;
805
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000806 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Mike Frysingerbfc0fae2009-03-26 18:14:16 +0000807
808 if (!BB_MMU) {
809 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
810 return;
811 }
812
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000813 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000814 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000815 return;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000816 G.ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000817 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000818 if (ENABLE_HUSH_JOB)
819 die_sleep = 0; /* let nofork's xfuncs die */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +0000820 bb_setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000821 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000822 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000823 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000824 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000825 /* return to nofork, it will eventually exit now,
826 * not return back to shell */
827 return;
828 }
829 /* parent */
830 /* finish filling up pipe info */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000831 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000832 G.toplevel_list->cmds[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000833 /* parent needs to longjmp out of running nofork.
834 * we will "return" exitcode 0, with child put in background */
835// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000836 debug_printf_jobs("siglongjmp in parent\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +0000837 siglongjmp(G.toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000838}
839
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000840/* Restores tty foreground process group, and exits.
841 * May be called as signal handler for fatal signal
842 * (will faithfully resend signal to itself, producing correct exit state)
843 * or called directly with -EXITCODE.
844 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000845static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000846static void sigexit(int sig)
847{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000848 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000849 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000850
Denis Vlasenko87a86552008-07-29 19:43:10 +0000851#if ENABLE_HUSH_INTERACTIVE
852 if (G.interactive_fd)
853 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
854#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000855
856 /* Not a signal, just exit */
857 if (sig <= 0)
858 _exit(- sig);
859
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000860 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000861}
862
863/* Restores tty foreground process group, and exits. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000864static void hush_exit(int exitcode) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000865static void hush_exit(int exitcode)
866{
867 fflush(NULL); /* flush all streams */
868 sigexit(- (exitcode & 0xff));
869}
870
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000871#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000872
873#define set_fatal_sighandler(handler) ((void)0)
874#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000875#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000876
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000877#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000878
879
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000880static const char *set_cwd(void)
881{
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000882 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
883 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +0000884 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000885 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000886 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
887 if (!G.cwd)
888 G.cwd = bb_msg_unknown;
889 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000890}
891
Denis Vlasenko83506862007-11-23 13:11:42 +0000892
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000893/* Get/check local shell variables */
894static struct variable *get_local_var(const char *name)
895{
896 struct variable *cur;
897 int len;
898
899 if (!name)
900 return NULL;
901 len = strlen(name);
902 for (cur = G.top_var; cur; cur = cur->next) {
903 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
904 return cur;
905 }
906 return NULL;
907}
908
909/* Basically useful version until someone wants to get fancier,
910 * see the bash man page under "Parameter Expansion" */
911static const char *lookup_param(const char *src)
912{
913 struct variable *var = get_local_var(src);
914 if (var)
915 return strchr(var->varstr, '=') + 1;
916 return NULL;
917}
918
919/* str holds "NAME=VAL" and is expected to be malloced.
920 * We take ownership of it. */
921static int set_local_var(char *str, int flg_export)
922{
923 struct variable *cur;
924 char *value;
925 int name_len;
926
927 value = strchr(str, '=');
928 if (!value) { /* not expected to ever happen? */
929 free(str);
930 return -1;
931 }
932
933 name_len = value - str + 1; /* including '=' */
934 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
935 while (1) {
936 if (strncmp(cur->varstr, str, name_len) != 0) {
937 if (!cur->next) {
938 /* Bail out. Note that now cur points
939 * to last var in linked list */
940 break;
941 }
942 cur = cur->next;
943 continue;
944 }
945 /* We found an existing var with this name */
946 *value = '\0';
947 if (cur->flg_read_only) {
948 bb_error_msg("%s: readonly variable", str);
949 free(str);
950 return -1;
951 }
952 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
953 unsetenv(str); /* just in case */
954 *value = '=';
955 if (strcmp(cur->varstr, str) == 0) {
956 free_and_exp:
957 free(str);
958 goto exp;
959 }
960 if (cur->max_len >= strlen(str)) {
961 /* This one is from startup env, reuse space */
962 strcpy(cur->varstr, str);
963 goto free_and_exp;
964 }
965 /* max_len == 0 signifies "malloced" var, which we can
966 * (and has to) free */
967 if (!cur->max_len)
968 free(cur->varstr);
969 cur->max_len = 0;
970 goto set_str_and_exp;
971 }
972
973 /* Not found - create next variable struct */
974 cur->next = xzalloc(sizeof(*cur));
975 cur = cur->next;
976
977 set_str_and_exp:
978 cur->varstr = str;
979 exp:
980 if (flg_export)
981 cur->flg_export = 1;
982 if (cur->flg_export) {
983 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
984 return putenv(cur->varstr);
985 }
986 return 0;
987}
988
989static void unset_local_var(const char *name)
990{
991 struct variable *cur;
992 struct variable *prev = prev; /* for gcc */
993 int name_len;
994
995 if (!name)
996 return;
997 name_len = strlen(name);
998 cur = G.top_var;
999 while (cur) {
1000 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1001 if (cur->flg_read_only) {
1002 bb_error_msg("%s: readonly variable", name);
1003 return;
1004 }
1005 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1006 * is ro, and we cannot reach this code on the 1st pass */
1007 prev->next = cur->next;
1008 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1009 bb_unsetenv(cur->varstr);
1010 if (!cur->max_len)
1011 free(cur->varstr);
1012 free(cur);
1013 return;
1014 }
1015 prev = cur;
1016 cur = cur->next;
1017 }
1018}
1019
1020
1021/*
1022 * in_str support
1023 */
1024static int static_get(struct in_str *i)
1025{
1026 int ch = *i->p++;
1027 if (ch == '\0') return EOF;
1028 return ch;
1029}
1030
1031static int static_peek(struct in_str *i)
1032{
1033 return *i->p;
1034}
1035
1036#if ENABLE_HUSH_INTERACTIVE
1037
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001038static void cmdedit_set_initial_prompt(void)
1039{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001040 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1041 G.PS1 = getenv("PS1");
1042 if (G.PS1 == NULL)
1043 G.PS1 = "\\w \\$ ";
1044 } else
1045 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001046}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001047
1048static const char* setup_prompt_string(int promptmode)
1049{
1050 const char *prompt_str;
1051 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001052 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1053 /* Set up the prompt */
1054 if (promptmode == 0) { /* PS1 */
1055 free((char*)G.PS1);
1056 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1057 prompt_str = G.PS1;
1058 } else
1059 prompt_str = G.PS2;
1060 } else
1061 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001062 debug_printf("result '%s'\n", prompt_str);
1063 return prompt_str;
1064}
1065
1066static void get_user_input(struct in_str *i)
1067{
1068 int r;
1069 const char *prompt_str;
1070
1071 prompt_str = setup_prompt_string(i->promptmode);
1072#if ENABLE_FEATURE_EDITING
1073 /* Enable command line editing only while a command line
1074 * is actually being read */
1075 do {
1076 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1077 } while (r == 0); /* repeat if Ctrl-C */
1078 i->eof_flag = (r < 0);
1079 if (i->eof_flag) { /* EOF/error detected */
1080 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1081 G.user_input_buf[1] = '\0';
1082 }
1083#else
1084 fputs(prompt_str, stdout);
1085 fflush(stdout);
1086 G.user_input_buf[0] = r = fgetc(i->file);
1087 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1088 i->eof_flag = (r == EOF);
1089#endif
1090 i->p = G.user_input_buf;
1091}
1092
1093#endif /* INTERACTIVE */
1094
1095/* This is the magic location that prints prompts
1096 * and gets data back from the user */
1097static int file_get(struct in_str *i)
1098{
1099 int ch;
1100
1101 /* If there is data waiting, eat it up */
1102 if (i->p && *i->p) {
1103#if ENABLE_HUSH_INTERACTIVE
1104 take_cached:
1105#endif
1106 ch = *i->p++;
1107 if (i->eof_flag && !*i->p)
1108 ch = EOF;
1109 } else {
1110 /* need to double check i->file because we might be doing something
1111 * more complicated by now, like sourcing or substituting. */
1112#if ENABLE_HUSH_INTERACTIVE
1113 if (G.interactive_fd && i->promptme && i->file == stdin) {
1114 do {
1115 get_user_input(i);
1116 } while (!*i->p); /* need non-empty line */
1117 i->promptmode = 1; /* PS2 */
1118 i->promptme = 0;
1119 goto take_cached;
1120 }
1121#endif
1122 ch = fgetc(i->file);
1123 }
1124 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1125#if ENABLE_HUSH_INTERACTIVE
1126 if (ch == '\n')
1127 i->promptme = 1;
1128#endif
1129 return ch;
1130}
1131
1132/* All the callers guarantee this routine will never be
1133 * used right after a newline, so prompting is not needed.
1134 */
1135static int file_peek(struct in_str *i)
1136{
1137 int ch;
1138 if (i->p && *i->p) {
1139 if (i->eof_flag && !i->p[1])
1140 return EOF;
1141 return *i->p;
1142 }
1143 ch = fgetc(i->file);
1144 i->eof_flag = (ch == EOF);
1145 i->peek_buf[0] = ch;
1146 i->peek_buf[1] = '\0';
1147 i->p = i->peek_buf;
1148 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1149 return ch;
1150}
1151
1152static void setup_file_in_str(struct in_str *i, FILE *f)
1153{
1154 i->peek = file_peek;
1155 i->get = file_get;
1156#if ENABLE_HUSH_INTERACTIVE
1157 i->promptme = 1;
1158 i->promptmode = 0; /* PS1 */
1159#endif
1160 i->file = f;
1161 i->p = NULL;
1162}
1163
1164static void setup_string_in_str(struct in_str *i, const char *s)
1165{
1166 i->peek = static_peek;
1167 i->get = static_get;
1168#if ENABLE_HUSH_INTERACTIVE
1169 i->promptme = 1;
1170 i->promptmode = 0; /* PS1 */
1171#endif
1172 i->p = s;
1173 i->eof_flag = 0;
1174}
1175
1176
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001177/*
1178 * o_string support
1179 */
1180#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001181
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001182static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001183{
1184 o->length = 0;
1185 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001186 if (o->data)
1187 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001188}
1189
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001190static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001191{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001192 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001193 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001194}
1195
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001196static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001197{
1198 if (o->length + len > o->maxlen) {
1199 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1200 o->data = xrealloc(o->data, 1 + o->maxlen);
1201 }
1202}
1203
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001204static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001205{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001206 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1207 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001208 o->data[o->length] = ch;
1209 o->length++;
1210 o->data[o->length] = '\0';
1211}
1212
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001213static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001214{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001215 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001216 memcpy(&o->data[o->length], str, len);
1217 o->length += len;
1218 o->data[o->length] = '\0';
1219}
1220
Denis Vlasenko55789c62008-06-18 16:30:42 +00001221static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1222{
1223 while (len) {
1224 o_addchr(o, *str);
1225 if (*str++ == '\\'
1226 && (*str != '*' && *str != '?' && *str != '[')
1227 ) {
1228 o_addchr(o, '\\');
1229 }
1230 len--;
1231 }
1232}
1233
Eric Andersen25f27032001-04-26 23:22:31 +00001234/* My analysis of quoting semantics tells me that state information
1235 * is associated with a destination, not a source.
1236 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001237static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001238{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001239 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001240 char *found = strchr("*?[\\", ch);
1241 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001242 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001243 o_grow_by(o, sz);
1244 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001245 o->data[o->length] = '\\';
1246 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001247 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001248 o->data[o->length] = ch;
1249 o->length++;
1250 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001251}
1252
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001253static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001254{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001255 int sz = 1;
1256 if (o->o_quote && strchr("*?[\\", ch)) {
1257 sz++;
1258 o->data[o->length] = '\\';
1259 o->length++;
1260 }
1261 o_grow_by(o, sz);
1262 o->data[o->length] = ch;
1263 o->length++;
1264 o->data[o->length] = '\0';
1265}
1266
1267static void o_addQstr(o_string *o, const char *str, int len)
1268{
1269 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001270 o_addstr(o, str, len);
1271 return;
1272 }
1273 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001274 char ch;
1275 int sz;
1276 int ordinary_cnt = strcspn(str, "*?[\\");
1277 if (ordinary_cnt > len) /* paranoia */
1278 ordinary_cnt = len;
1279 o_addstr(o, str, ordinary_cnt);
1280 if (ordinary_cnt == len)
1281 return;
1282 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001283 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001284
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001285 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001286 sz = 1;
1287 if (ch) { /* it is necessarily one of "*?[\\" */
1288 sz++;
1289 o->data[o->length] = '\\';
1290 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001291 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001292 o_grow_by(o, sz);
1293 o->data[o->length] = ch;
1294 o->length++;
1295 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001296 }
1297}
1298
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001299/* A special kind of o_string for $VAR and `cmd` expansion.
1300 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001301 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001302 * list[i] contains an INDEX (int!) into this string data.
1303 * It means that if list[] needs to grow, data needs to be moved higher up
1304 * but list[i]'s need not be modified.
1305 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001306 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001307 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1308 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001309#if DEBUG_EXPAND || DEBUG_GLOB
1310static void debug_print_list(const char *prefix, o_string *o, int n)
1311{
1312 char **list = (char**)o->data;
1313 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1314 int i = 0;
1315 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1316 prefix, list, n, string_start, o->length, o->maxlen);
1317 while (i < n) {
1318 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1319 o->data + (int)list[i] + string_start,
1320 o->data + (int)list[i] + string_start);
1321 i++;
1322 }
1323 if (n) {
1324 const char *p = o->data + (int)list[n - 1] + string_start;
Mike Frysingerd006edb2009-03-28 12:43:53 +00001325 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001326 }
1327}
1328#else
1329#define debug_print_list(prefix, o, n) ((void)0)
1330#endif
1331
1332/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1333 * in list[n] so that it points past last stored byte so far.
1334 * It returns n+1. */
1335static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001336{
1337 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001338 int string_start;
1339 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001340
1341 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001342 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1343 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001344 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001345 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001346 /* list[n] points to string_start, make space for 16 more pointers */
1347 o->maxlen += 0x10 * sizeof(list[0]);
1348 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001349 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001350 memmove(list + n + 0x10, list + n, string_len);
1351 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001352 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001353 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001354 } else {
1355 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001356 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1357 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001358 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001359 o->has_empty_slot = 0;
1360 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001361 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001362 return n + 1;
1363}
1364
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001365/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001366static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001367{
1368 char **list = (char**)o->data;
1369 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1370
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001371 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001372}
1373
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001374/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001375 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001376static int o_glob(o_string *o, int n)
1377{
1378 glob_t globdata;
1379 int gr;
1380 char *pattern;
1381
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001382 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001383 if (!o->data)
1384 return o_save_ptr_helper(o, n);
1385 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001386 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001387 if (!glob_needed(pattern)) {
1388 literal:
1389 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001390 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001391 return o_save_ptr_helper(o, n);
1392 }
1393
1394 memset(&globdata, 0, sizeof(globdata));
1395 gr = glob(pattern, 0, NULL, &globdata);
1396 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1397 if (gr == GLOB_NOSPACE)
1398 bb_error_msg_and_die("out of memory during glob");
1399 if (gr == GLOB_NOMATCH) {
1400 globfree(&globdata);
1401 goto literal;
1402 }
1403 if (gr != 0) { /* GLOB_ABORTED ? */
1404//TODO: testcase for bad glob pattern behavior
1405 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1406 }
1407 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1408 char **argv = globdata.gl_pathv;
1409 o->length = pattern - o->data; /* "forget" pattern */
1410 while (1) {
1411 o_addstr(o, *argv, strlen(*argv) + 1);
1412 n = o_save_ptr_helper(o, n);
1413 argv++;
1414 if (!*argv)
1415 break;
1416 }
1417 }
1418 globfree(&globdata);
1419 if (DEBUG_GLOB)
1420 debug_print_list("o_glob returning", o, n);
1421 return n;
1422}
1423
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001424/* If o->o_glob == 1, glob the string so far remembered.
1425 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001426static int o_save_ptr(o_string *o, int n)
1427{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001428 if (o->o_glob) { /* if globbing is requested */
1429 /* If o->has_empty_slot, list[n] was already globbed
1430 * (if it was requested back then when it was filled)
1431 * so don't do that again! */
1432 if (!o->has_empty_slot)
1433 return o_glob(o, n); /* o_save_ptr_helper is inside */
1434 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001435 return o_save_ptr_helper(o, n);
1436}
1437
1438/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001439static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001440{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001441 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001442 int string_start;
1443
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001444 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1445 if (DEBUG_EXPAND)
1446 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001447 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001448 list = (char**)o->data;
1449 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1450 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001451 while (n) {
1452 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001453 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001454 }
1455 return list;
1456}
1457
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001458
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001459/* expand_strvec_to_strvec() takes a list of strings, expands
1460 * all variable references within and returns a pointer to
1461 * a list of expanded strings, possibly with larger number
1462 * of strings. (Think VAR="a b"; echo $VAR).
1463 * This new list is allocated as a single malloc block.
1464 * NULL-terminated list of char* pointers is at the beginning of it,
1465 * followed by strings themself.
1466 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001467
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001468/* Store given string, finalizing the word and starting new one whenever
1469 * we encounter IFS char(s). This is used for expanding variable values.
1470 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1471static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001472{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001473 while (1) {
1474 int word_len = strcspn(str, G.ifs);
1475 if (word_len) {
1476 if (output->o_quote || !output->o_glob)
1477 o_addQstr(output, str, word_len);
1478 else /* protect backslashes against globbing up :) */
1479 o_addstr_duplicate_backslash(output, str, word_len);
1480 str += word_len;
1481 }
1482 if (!*str) /* EOL - do not finalize word */
1483 break;
1484 o_addchr(output, '\0');
1485 debug_print_list("expand_on_ifs", output, n);
1486 n = o_save_ptr(output, n);
1487 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001488 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001489 debug_print_list("expand_on_ifs[1]", output, n);
1490 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001491}
1492
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001493#if ENABLE_HUSH_TICK
1494static int process_command_subs(o_string *dest,
1495 struct in_str *input, const char *subst_end);
Eric Andersen25f27032001-04-26 23:22:31 +00001496#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001497
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001498/* Expand all variable references in given string, adding words to list[]
1499 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1500 * to be filled). This routine is extremely tricky: has to deal with
1501 * variables/parameters with whitespace, $* and $@, and constructs like
1502 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1503static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001504{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001505 /* or_mask is either 0 (normal case) or 0x80
1506 * (expansion of right-hand side of assignment == 1-element expand.
1507 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001508
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001509 char first_ch, ored_ch;
1510 int i;
1511 const char *val;
1512 char *p;
1513
1514 ored_ch = 0;
1515
1516 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1517 debug_print_list("expand_vars_to_list", output, n);
1518 n = o_save_ptr(output, n);
1519 debug_print_list("expand_vars_to_list[0]", output, n);
1520
1521 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1522#if ENABLE_HUSH_TICK
1523 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001524#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001525 o_addstr(output, arg, p - arg);
1526 debug_print_list("expand_vars_to_list[1]", output, n);
1527 arg = ++p;
1528 p = strchr(p, SPECIAL_VAR_SYMBOL);
1529
1530 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1531 /* "$@" is special. Even if quoted, it can still
1532 * expand to nothing (not even an empty string) */
1533 if ((first_ch & 0x7f) != '@')
1534 ored_ch |= first_ch;
1535 val = NULL;
1536 switch (first_ch & 0x7f) {
1537 /* Highest bit in first_ch indicates that var is double-quoted */
1538 case '$': /* pid */
1539 val = utoa(G.root_pid);
1540 break;
1541 case '!': /* bg pid */
1542 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1543 break;
1544 case '?': /* exitcode */
1545 val = utoa(G.last_return_code);
1546 break;
1547 case '#': /* argc */
1548 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1549 break;
1550 case '*':
1551 case '@':
1552 i = 1;
1553 if (!G.global_argv[i])
1554 break;
1555 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1556 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1557 smallint sv = output->o_quote;
1558 /* unquoted var's contents should be globbed, so don't quote */
1559 output->o_quote = 0;
1560 while (G.global_argv[i]) {
1561 n = expand_on_ifs(output, n, G.global_argv[i]);
1562 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1563 if (G.global_argv[i++][0] && G.global_argv[i]) {
1564 /* this argv[] is not empty and not last:
1565 * put terminating NUL, start new word */
1566 o_addchr(output, '\0');
1567 debug_print_list("expand_vars_to_list[2]", output, n);
1568 n = o_save_ptr(output, n);
1569 debug_print_list("expand_vars_to_list[3]", output, n);
1570 }
1571 }
1572 output->o_quote = sv;
1573 } else
1574 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1575 * and in this case should treat it like '$*' - see 'else...' below */
1576 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1577 while (1) {
1578 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1579 if (++i >= G.global_argc)
1580 break;
1581 o_addchr(output, '\0');
1582 debug_print_list("expand_vars_to_list[4]", output, n);
1583 n = o_save_ptr(output, n);
1584 }
1585 } else { /* quoted $*: add as one word */
1586 while (1) {
1587 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1588 if (!G.global_argv[++i])
1589 break;
1590 if (G.ifs[0])
1591 o_addchr(output, G.ifs[0]);
1592 }
1593 }
1594 break;
1595 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1596 /* "Empty variable", used to make "" etc to not disappear */
1597 arg++;
1598 ored_ch = 0x80;
1599 break;
1600#if ENABLE_HUSH_TICK
1601 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1602 struct in_str input;
1603 *p = '\0';
1604 arg++;
1605//TODO: can we just stuff it into "output" directly?
1606 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1607 setup_string_in_str(&input, arg);
1608 process_command_subs(&subst_result, &input, NULL);
1609 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1610 val = subst_result.data;
1611 goto store_val;
Eric Andersen25f27032001-04-26 23:22:31 +00001612 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001613#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001614 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1615 *p = '\0';
1616 arg[0] = first_ch & 0x7f;
1617 if (isdigit(arg[0])) {
1618 i = xatoi_u(arg);
1619 if (i < G.global_argc)
1620 val = G.global_argv[i];
1621 /* else val remains NULL: $N with too big N */
1622 } else
1623 val = lookup_param(arg);
1624 arg[0] = first_ch;
1625#if ENABLE_HUSH_TICK
1626 store_val:
1627#endif
1628 *p = SPECIAL_VAR_SYMBOL;
1629 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1630 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1631 if (val) {
1632 /* unquoted var's contents should be globbed, so don't quote */
1633 smallint sv = output->o_quote;
1634 output->o_quote = 0;
1635 n = expand_on_ifs(output, n, val);
1636 val = NULL;
1637 output->o_quote = sv;
1638 }
1639 } else { /* quoted $VAR, val will be appended below */
1640 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1641 }
1642 }
1643 if (val) {
1644 o_addQstr(output, val, strlen(val));
1645 }
1646
1647#if ENABLE_HUSH_TICK
1648 o_free(&subst_result);
1649#endif
1650 arg = ++p;
1651 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1652
1653 if (arg[0]) {
1654 debug_print_list("expand_vars_to_list[a]", output, n);
1655 /* this part is literal, and it was already pre-quoted
1656 * if needed (much earlier), do not use o_addQstr here! */
1657 o_addstr(output, arg, strlen(arg) + 1);
1658 debug_print_list("expand_vars_to_list[b]", output, n);
1659 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1660 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1661 ) {
1662 n--;
1663 /* allow to reuse list[n] later without re-growth */
1664 output->has_empty_slot = 1;
1665 } else {
1666 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00001667 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001668 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001669}
1670
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001671static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001672{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001673 int n;
1674 char **list;
1675 char **v;
1676 o_string output = NULL_O_STRING;
1677
1678 if (or_mask & 0x100) {
1679 output.o_quote = 1; /* protect against globbing for "$var" */
1680 /* (unquoted $var will temporarily switch it off) */
1681 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001682 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001683
1684 n = 0;
1685 v = argv;
1686 while (*v) {
1687 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1688 v++;
1689 }
1690 debug_print_list("expand_variables", &output, n);
1691
1692 /* output.data (malloced in one block) gets returned in "list" */
1693 list = o_finalize_list(&output, n);
1694 debug_print_strings("expand_variables[1]", list);
1695 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00001696}
1697
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001698static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001699{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001700 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00001701}
1702
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001703/* Used for expansion of right hand of assignments */
1704/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1705 * "v=/bin/c*" */
1706static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001707{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001708 char *argv[2], **list;
1709
1710 argv[0] = (char*)str;
1711 argv[1] = NULL;
1712 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1713 if (HUSH_DEBUG)
1714 if (!list[0] || list[1])
1715 bb_error_msg_and_die("BUG in varexp2");
1716 /* actually, just move string 2*sizeof(char*) bytes back */
1717 overlapping_strcpy((char*)list, list[0]);
1718 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1719 return (char*)list;
1720}
1721
1722/* Used for "eval" builtin */
1723static char* expand_strvec_to_string(char **argv)
1724{
1725 char **list;
1726
1727 list = expand_variables(argv, 0x80);
1728 /* Convert all NULs to spaces */
1729 if (list[0]) {
1730 int n = 1;
1731 while (list[n]) {
1732 if (HUSH_DEBUG)
1733 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1734 bb_error_msg_and_die("BUG in varexp3");
1735 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1736 n++;
1737 }
1738 }
1739 overlapping_strcpy((char*)list, list[0]);
1740 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1741 return (char*)list;
1742}
1743
1744static char **expand_assignments(char **argv, int count)
1745{
1746 int i;
1747 char **p = NULL;
1748 /* Expand assignments into one string each */
1749 for (i = 0; i < count; i++) {
1750 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1751 }
1752 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00001753}
1754
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001755
Eric Andersen25f27032001-04-26 23:22:31 +00001756/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1757 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001758static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00001759{
1760 int openfd, mode;
1761 struct redir_struct *redir;
1762
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001763 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001764 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001765 /* something went wrong in the parse. Pretend it didn't happen */
1766 continue;
1767 }
Eric Andersen25f27032001-04-26 23:22:31 +00001768 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001769 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001770 mode = redir_table[redir->rd_type].mode;
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00001771//TODO: check redir for names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001772 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001773 openfd = open_or_warn(p, mode);
1774 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001775 if (openfd < 0) {
1776 /* this could get lost if stderr has been redirected, but
1777 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001778 return 1;
1779 }
1780 } else {
1781 openfd = redir->dup;
1782 }
1783
1784 if (openfd != redir->fd) {
1785 if (squirrel && redir->fd < 3) {
1786 squirrel[redir->fd] = dup(redir->fd);
1787 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001788 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001789 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001790 } else {
1791 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001792 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001793 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001794 }
Eric Andersen25f27032001-04-26 23:22:31 +00001795 }
1796 }
1797 return 0;
1798}
1799
1800static void restore_redirects(int squirrel[])
1801{
1802 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001803 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001804 fd = squirrel[i];
1805 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001806 /* We simply die on error */
1807 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001808 }
1809 }
1810}
1811
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001812
1813#if !defined(DEBUG_CLEAN)
1814#define free_pipe_list(head, indent) free_pipe_list(head)
1815#define free_pipe(pi, indent) free_pipe(pi)
1816#endif
1817static int free_pipe_list(struct pipe *head, int indent);
1818
1819/* return code is the exit status of the pipe */
1820static int free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001821{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001822 char **p;
1823 struct command *command;
1824 struct redir_struct *r, *rnext;
1825 int a, i, ret_code = 0;
1826
1827 if (pi->stopped_cmds > 0)
1828 return ret_code;
1829 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1830 for (i = 0; i < pi->num_cmds; i++) {
1831 command = &pi->cmds[i];
1832 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1833 if (command->argv) {
1834 for (a = 0, p = command->argv; *p; a++, p++) {
1835 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1836 }
1837 free_strings(command->argv);
1838 command->argv = NULL;
1839 } else if (command->group) {
1840 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1841 ret_code = free_pipe_list(command->group, indent+3);
1842 debug_printf_clean("%s end group\n", indenter(indent));
1843 } else {
1844 debug_printf_clean("%s (nil)\n", indenter(indent));
1845 }
1846 for (r = command->redirects; r; r = rnext) {
1847 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1848 if (r->dup == -1) {
1849 /* guard against the case >$FOO, where foo is unset or blank */
1850 if (r->rd_filename) {
1851 debug_printf_clean(" %s\n", r->rd_filename);
1852 free(r->rd_filename);
1853 r->rd_filename = NULL;
1854 }
1855 } else {
1856 debug_printf_clean("&%d\n", r->dup);
1857 }
1858 rnext = r->next;
1859 free(r);
1860 }
1861 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001862 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001863 free(pi->cmds); /* children are an array, they get freed all at once */
1864 pi->cmds = NULL;
1865#if ENABLE_HUSH_JOB
1866 free(pi->cmdtext);
1867 pi->cmdtext = NULL;
1868#endif
1869 return ret_code;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001870}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001871
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001872static int free_pipe_list(struct pipe *head, int indent)
1873{
1874 int rcode = 0; /* if list has no members */
1875 struct pipe *pi, *next;
1876
1877 for (pi = head; pi; pi = next) {
1878#if HAS_KEYWORDS
1879 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1880#endif
1881 rcode = free_pipe(pi, indent);
1882 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1883 next = pi->next;
1884 /*pi->next = NULL;*/
1885 free(pi);
1886 }
1887 return rcode;
1888}
1889
1890
1891#if !BB_MMU
1892typedef struct nommu_save_t {
1893 char **new_env;
1894 char **old_env;
1895 char **argv;
1896} nommu_save_t;
1897#else
1898#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1899 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1900#define pseudo_exec(nommu_save, command, argv_expanded) \
1901 pseudo_exec(command, argv_expanded)
1902#endif
1903
Denis Vlasenko05743d72008-02-10 12:10:08 +00001904/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001905 * Never returns.
1906 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001907 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001908 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001909static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001910static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00001911{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001912 int rcode;
1913 char **new_env;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001914 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001915
Denis Vlasenko1359da62007-04-21 23:27:30 +00001916 /* If a variable is assigned in a forest, and nobody listens,
1917 * was it ever really set?
1918 */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001919 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001920 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001921
Denis Vlasenko9504e442008-10-29 01:19:15 +00001922 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001923#if BB_MMU
1924 putenv_all(new_env);
1925 free(new_env); /* optional */
1926#else
1927 nommu_save->new_env = new_env;
1928 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00001929#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001930 if (argv_expanded) {
1931 argv = argv_expanded;
1932 } else {
1933 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001934#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001935 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00001936#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00001937 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001938
Denis Vlasenko1359da62007-04-21 23:27:30 +00001939 /*
1940 * Check if the command matches any of the builtins.
1941 * Depending on context, this might be redundant. But it's
1942 * easier to waste a few CPU cycles than it is to figure out
1943 * if this is one of those cases.
1944 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001945 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001946 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001947 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001948 rcode = x->function(argv);
1949 fflush(stdout);
1950 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001951 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001952 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001953
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001954 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001955#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001956 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001957 int a = find_applet_by_name(argv[0]);
1958 if (a >= 0) {
1959 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001960 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001961// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1962 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001963 }
1964 /* re-exec ourselves with the new arguments */
1965 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001966 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001967 /* If they called chroot or otherwise made the binary no longer
1968 * executable, fall through */
1969 }
1970 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001971#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001972
1973 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001974 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00001975 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001976 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001977}
1978
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001979static int run_list(struct pipe *pi);
1980
Denis Vlasenko05743d72008-02-10 12:10:08 +00001981/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001982 */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001983static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001984static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001985{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001986 if (command->argv)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00001987 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001988
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001989 if (command->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001990#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001991 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001992#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001993 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001994 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00001995 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001996 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001997 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001998 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001999#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002000 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002001
2002 /* Can happen. See what bash does with ">foo" by itself. */
2003 debug_printf("trying to pseudo_exec null command\n");
2004 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002005}
2006
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002007#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002008static const char *get_cmdtext(struct pipe *pi)
2009{
2010 char **argv;
2011 char *p;
2012 int len;
2013
2014 /* This is subtle. ->cmdtext is created only on first backgrounding.
2015 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002016 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002017 if (pi->cmdtext)
2018 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002019 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002020 if (!argv || !argv[0]) {
2021 pi->cmdtext = xzalloc(1);
2022 return pi->cmdtext;
2023 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002024
2025 len = 0;
2026 do len += strlen(*argv) + 1; while (*++argv);
2027 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002028 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002029 do {
2030 len = strlen(*argv);
2031 memcpy(p, *argv, len);
2032 p += len;
2033 *p++ = ' ';
2034 } while (*++argv);
2035 p[-1] = '\0';
2036 return pi->cmdtext;
2037}
2038
Eric Andersenbafd94f2001-05-02 16:11:59 +00002039static void insert_bg_job(struct pipe *pi)
2040{
2041 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002042 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002043
2044 /* Linear search for the ID of the job to use */
2045 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002046 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002047 if (thejob->jobid >= pi->jobid)
2048 pi->jobid = thejob->jobid + 1;
2049
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002050 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002051 if (!G.job_list) {
2052 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002053 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002054 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002055 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002056 thejob->next = xmalloc(sizeof(*thejob));
2057 thejob = thejob->next;
2058 }
2059
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002060 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002061 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002062 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2063 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2064 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002065// TODO: do we really need to have so many fields which are just dead weight
2066// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002067 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002068 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002069 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002070 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002071 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002072
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002073 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002074 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002075 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2076 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002077 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002078}
2079
Eric Andersenbafd94f2001-05-02 16:11:59 +00002080static void remove_bg_job(struct pipe *pi)
2081{
2082 struct pipe *prev_pipe;
2083
Denis Vlasenko87a86552008-07-29 19:43:10 +00002084 if (pi == G.job_list) {
2085 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002086 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002087 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002088 while (prev_pipe->next != pi)
2089 prev_pipe = prev_pipe->next;
2090 prev_pipe->next = pi->next;
2091 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002092 if (G.job_list)
2093 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002094 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002095 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002096}
Eric Andersen028b65b2001-06-28 01:10:11 +00002097
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002098/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002099static void delete_finished_bg_job(struct pipe *pi)
2100{
2101 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002102 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002103 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002104 free(pi);
2105}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002106#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002107
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002108/* Check to see if any processes have exited -- if they
2109 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002110static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002111{
Eric Andersenc798b072001-06-22 06:23:03 +00002112 int attributes;
2113 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002114#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002115 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002116#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002117 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002118 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002119
Eric Andersenc798b072001-06-22 06:23:03 +00002120 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002121 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002122 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002123
Denis Vlasenko1359da62007-04-21 23:27:30 +00002124/* Do we do this right?
2125 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002126 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002127 * [3]+ Stopped sleep 20 | false
2128 * bash-3.00# echo $?
2129 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2130 */
2131
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002132//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2133//are stopped. Testcase: "cat | cat" in a script (not on command line)
2134// + killall -STOP cat
2135
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002136 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00002137// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00002138 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002139 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002140 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002141#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002142 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002143 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002144 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2145 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002146 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002147 childpid, WTERMSIG(status), WEXITSTATUS(status));
2148 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002149 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002150 childpid, WEXITSTATUS(status));
2151#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002152 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002153 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002154 for (i = 0; i < fg_pipe->num_cmds; i++) {
2155 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2156 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002157 continue;
2158 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2159 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002160 fg_pipe->cmds[i].pid = 0;
2161 fg_pipe->alive_cmds--;
2162 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002163 /* last process gives overall exitstatus */
2164 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002165 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002166 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002167 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002168 fg_pipe->cmds[i].is_stopped = 1;
2169 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002170 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002171 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2172 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2173 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002174 /* All processes in fg pipe have exited/stopped */
2175#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002176 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002177 insert_bg_job(fg_pipe);
2178#endif
2179 return rcode;
2180 }
2181 /* There are still running processes in the fg pipe */
2182 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002183 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002184 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002185 }
2186
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002187#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002188 /* We asked to wait for bg or orphaned children */
2189 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002190 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002191 for (i = 0; i < pi->num_cmds; i++) {
2192 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002193 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002194 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002195 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002196 /* Happens when shell is used as init process (init=/bin/sh) */
2197 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002198 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002199
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002200 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002201 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002202 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002203 pi->cmds[i].pid = 0;
2204 pi->alive_cmds--;
2205 if (!pi->alive_cmds) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002206 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002207 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002208 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002209 }
2210 } else {
2211 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002212 pi->cmds[i].is_stopped = 1;
2213 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002214 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002215#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002216 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002217
Denis Vlasenko1359da62007-04-21 23:27:30 +00002218 /* wait found no children or failed */
2219
2220 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002221 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002222 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002223}
2224
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002225#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002226static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2227{
2228 pid_t p;
2229 int rcode = checkjobs(fg_pipe);
2230 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002231 p = getpgid(0); /* pgid of our process */
2232 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002233 tcsetpgrp(G.interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002234 return rcode;
2235}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002236#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002237
Denis Vlasenko05743d72008-02-10 12:10:08 +00002238/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00002239 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002240 *
2241 * return code is normally -1, when the caller has to wait for children
2242 * to finish to determine the exit status of the pipe. If the pipe
2243 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002244 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002245 * return value.
2246 *
2247 * The input of the pipe is always stdin, the output is always
2248 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2249 * because it tries to avoid running the command substitution in
2250 * subshell, when that is in fact necessary. The subshell process
2251 * now has its stdout directed to the input of the appropriate pipe,
2252 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00002253 *
2254 * Returns -1 only if started some children. IOW: we have to
2255 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00002256 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002257static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002258{
2259 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002260 int nextin;
2261 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002262 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002263 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002264 char **argv;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00002265 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002266 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002267 /* it is not always needed, but we aim to smaller code */
2268 int squirrel[] = { -1, -1, -1 };
2269 int rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002270 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00002271
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002272 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002273
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002274#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00002275 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002276#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002277 pi->alive_cmds = 1;
2278 pi->stopped_cmds = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002279
2280 /* Check if this is a simple builtin (not part of a pipe).
2281 * Builtins within pipes have to fork anyway, and are handled in
2282 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2283 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002284 command = &(pi->cmds[0]);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002285
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002286#if ENABLE_HUSH_FUNCTIONS
2287 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2288 /* We "execute" function definition */
2289 bb_error_msg("here we ought to remember function definition, and go on");
2290 return EXIT_SUCCESS;
2291 }
2292#endif
2293
2294 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
Eric Andersen04407e52001-06-07 16:42:05 +00002295 debug_printf("non-subshell grouping\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002296 setup_redirects(command, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002297 debug_printf_exec(": run_list\n");
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002298 rcode = run_list(command->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00002299 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002300 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002301 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00002302 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002303 }
2304
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002305 argv = command->argv;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002306 argv_expanded = NULL;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002307
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002308 if (single_and_fg && argv != NULL) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002309 char **new_env = NULL;
2310 char **old_env = NULL;
2311
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002312 i = command->assignment_cnt;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002313 if (i != 0 && argv[i] == NULL) {
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002314 /* assignments, but no command: set local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002315 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002316 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002317 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002318 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00002319 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002320 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
Eric Andersen78a7c992001-05-15 16:30:25 +00002321 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002322
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002323 /* Expand the rest into (possibly) many strings each */
2324 argv_expanded = expand_strvec_to_strvec(argv + i);
2325
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00002326 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002327 if (strcmp(argv_expanded[0], x->cmd) != 0)
2328 continue;
2329 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2330 debug_printf("exec with redirects only\n");
2331 setup_redirects(command, NULL);
2332 rcode = EXIT_SUCCESS;
2333 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00002334 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002335 debug_printf("builtin inline %s\n", argv_expanded[0]);
2336 /* XXX setup_redirects acts on file descriptors, not FILEs.
2337 * This is perfect for work that comes after exec().
2338 * Is it really safe for inline use? Experimentally,
2339 * things seem to work with glibc. */
2340 setup_redirects(command, squirrel);
2341 new_env = expand_assignments(argv, command->assignment_cnt);
2342 old_env = putenv_all_and_save_old(new_env);
2343 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2344 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002345#if ENABLE_FEATURE_SH_STANDALONE
2346 clean_up_and_ret:
2347#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002348 restore_redirects(squirrel);
2349 free_strings_and_unsetenv(new_env, 1);
2350 putenv_all(old_env);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002351 free(old_env); /* not free_strings()! */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002352 clean_up_and_ret1:
2353 free(argv_expanded);
2354 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2355 debug_printf_exec("run_pipe return %d\n", rcode);
2356 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002357 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002358#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002359 i = find_applet_by_name(argv_expanded[0]);
2360 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2361 setup_redirects(command, squirrel);
2362 save_nofork_data(&G.nofork_save);
2363 new_env = expand_assignments(argv, command->assignment_cnt);
2364 old_env = putenv_all_and_save_old(new_env);
2365 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2366 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2367 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00002368 }
2369#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002370 }
2371
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002372 /* NB: argv_expanded may already be created, and that
2373 * might include `cmd` runs! Do not rerun it! We *must*
2374 * use argv_expanded if it's non-NULL */
2375
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002376 /* Disable job control signals for shell (parent) and
2377 * for initial child code after fork */
2378 set_jobctrl_sighandler(SIG_IGN);
2379
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002380 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002381 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002382 nextin = 0;
2383
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002384 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00002385#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002386 volatile nommu_save_t nommu_save;
2387 nommu_save.new_env = NULL;
2388 nommu_save.old_env = NULL;
2389 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002390#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002391 command = &(pi->cmds[i]);
2392 if (command->argv) {
2393 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002394 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002395 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002396
2397 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002398 pipefds[0] = 0;
2399 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002400 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002401 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00002402
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002403 command->pid = BB_MMU ? fork() : vfork();
2404 if (!command->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00002405 if (ENABLE_HUSH_JOB)
2406 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002407#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002408 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00002409 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002410 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002411 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002412 /* Don't do pgrp restore anymore on fatal signals */
2413 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002414 pgrp = pi->pgrp;
2415 if (pgrp < 0) /* true for 1st process only */
2416 pgrp = getpid();
2417 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002418 /* We do it in *every* child, not just first,
2419 * to avoid races */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002420 tcsetpgrp(G.interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002421 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002422 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002423#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00002424 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002425 xmove_fd(pipefds[1], 1); /* write end */
2426 if (pipefds[0] > 1)
2427 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00002428 /* Like bash, explicit redirects override pipes,
2429 * and the pipe fd is available for dup'ing. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002430 setup_redirects(command, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00002431
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002432 /* Restore default handlers just prior to exec */
2433 set_jobctrl_sighandler(SIG_DFL);
2434 set_misc_sighandler(SIG_DFL);
2435 signal(SIGCHLD, SIG_DFL);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002436 /* Stores to nommu_save list of env vars putenv'ed
2437 * (NOMMU, on MMU we don't need that) */
2438 /* cast away volatility... */
2439 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002440 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00002441 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002442 /* parent */
2443#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002444 /* Clean up after vforked child */
2445 free(nommu_save.argv);
2446 free_strings_and_unsetenv(nommu_save.new_env, 1);
2447 putenv_all(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002448#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002449 free(argv_expanded);
2450 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002451 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002452 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00002453 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002454 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002455 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002456#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002457 /* Second and next children need to know pid of first one */
2458 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002459 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002460#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002461 }
Eric Andersen25f27032001-04-26 23:22:31 +00002462
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002463 if (i)
2464 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002465 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002466 close(pipefds[1]); /* write end */
2467 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00002468 nextin = pipefds[0];
2469 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002470
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002471 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00002472 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2473 return 1;
2474 }
2475
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002476 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00002477 return -1;
2478}
2479
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002480#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002481static void debug_print_tree(struct pipe *pi, int lvl)
2482{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002483 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002484 [PIPE_SEQ] = "SEQ",
2485 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002486 [PIPE_OR ] = "OR" ,
2487 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002488 };
2489 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002490 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002491#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002492 [RES_IF ] = "IF" ,
2493 [RES_THEN ] = "THEN" ,
2494 [RES_ELIF ] = "ELIF" ,
2495 [RES_ELSE ] = "ELSE" ,
2496 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002497#endif
2498#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002499 [RES_FOR ] = "FOR" ,
2500 [RES_WHILE] = "WHILE",
2501 [RES_UNTIL] = "UNTIL",
2502 [RES_DO ] = "DO" ,
2503 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002504#endif
2505#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002506 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00002507#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002508#if ENABLE_HUSH_CASE
2509 [RES_CASE ] = "CASE" ,
2510 [RES_MATCH] = "MATCH",
2511 [RES_CASEI] = "CASEI",
2512 [RES_ESAC ] = "ESAC" ,
2513#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00002514 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002515 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002516 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002517 static const char *const GRPTYPE[] = {
2518 "()",
2519 "{}",
2520#if ENABLE_HUSH_FUNCTIONS
2521 "func()",
2522#endif
2523 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002524
2525 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002526
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002527 pin = 0;
2528 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002529 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2530 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002531 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002532 while (prn < pi->num_cmds) {
2533 struct command *command = &pi->cmds[prn];
2534 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002535
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002536 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2537 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002538 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00002539 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002540 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002541 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002542 prn++;
2543 continue;
2544 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002545 if (argv) while (*argv) {
2546 fprintf(stderr, " '%s'", *argv);
2547 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002548 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002549 fprintf(stderr, "\n");
2550 prn++;
2551 }
2552 pi = pi->next;
2553 pin++;
2554 }
2555}
2556#endif
2557
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002558/* NB: called by pseudo_exec, and therefore must not modify any
2559 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002560static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002561{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002562#if ENABLE_HUSH_CASE
2563 char *case_word = NULL;
2564#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002565#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002566 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002567 char *for_varname = NULL;
2568 char **for_lcur = NULL;
2569 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00002570#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002571 smallint flag_skip = 1;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002572 smalluint rcode = 0; /* probably just for compiler */
Denis Vlasenkod91afa32008-07-29 11:10:01 +00002573#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002574 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002575#else
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002576 enum { cond_code = 0, };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002577#endif
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002578 /*enum reserved_style*/ smallint rword = RES_NONE;
2579 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002580
Denis Vlasenko87a86552008-07-29 19:43:10 +00002581 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002582
Denis Vlasenko06810332007-05-21 23:30:54 +00002583#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002584 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002585 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2586 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002587 continue;
2588 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002589 if (cpipe->next == NULL) {
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002590 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002591 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002592 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002593 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002594 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002595 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002596 continue;
2597 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002598 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2599 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002600 ) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002601 syntax("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002602 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002603 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002604 }
2605 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002606#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002607
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002608 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00002609 * in order to return, no direct "return" statements please.
2610 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002611
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002612#if ENABLE_HUSH_JOB
2613 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2614 * We are saving state before entering outermost list ("while...done")
2615 * so that ctrl-Z will correctly background _entire_ outermost list,
2616 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002617 if (++G.run_list_level == 1 && G.interactive_fd) {
2618 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002619 /* ctrl-Z forked and we are parent; or ctrl-C.
2620 * Sighandler has longjmped us here */
2621 signal(SIGINT, SIG_IGN);
2622 signal(SIGTSTP, SIG_IGN);
2623 /* Restore level (we can be coming from deep inside
2624 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002625 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002626#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002627 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002628 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002629 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002630 }
2631#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002632 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002633 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2634 * Remember this child as background job */
2635 insert_bg_job(pi);
2636 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002637 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002638 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002639 }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00002640 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002641 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002642 rcode = 0;
2643 goto ret;
2644 }
2645 /* ctrl-Z handler will store pid etc in pi */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002646 G.toplevel_list = pi;
2647 G.ctrl_z_flag = 0;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002648#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00002649 G.nofork_save.saved = 0; /* in case we will run a nofork later */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002650#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002651 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002652 signal(SIGINT, handler_ctrl_c);
2653 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002654#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002655
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002656 /* Go through list of pipes, (maybe) executing them. */
2657 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002658 IF_HAS_KEYWORDS(rword = pi->res_word;)
2659 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002660 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2661 rword, cond_code, skip_more_for_this_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00002662#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00002663 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002664 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00002665 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002666 /* start of a loop: remember where loop starts */
2667 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002668 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002669 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002670#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002671 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002672 if (pi->followup == PIPE_SEQ)
2673 flag_skip = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002674 /* it is "<false> && CMD" or "<true> || CMD"
2675 * and we should not execute CMD */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002676 continue;
2677 }
2678 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002679 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002680#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002681 if (cond_code) {
2682 if (rword == RES_THEN) {
2683 /* "if <false> THEN cmd": skip cmd */
2684 continue;
2685 }
2686 } else {
2687 if (rword == RES_ELSE || rword == RES_ELIF) {
2688 /* "if <true> then ... ELSE/ELIF cmd":
2689 * skip cmd and all following ones */
2690 break;
2691 }
2692 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002693#endif
2694#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002695 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002696 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002697 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002698
2699 static const char encoded_dollar_at[] ALIGN1 = {
2700 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2701 }; /* encoded representation of "$@" */
2702 static const char *const encoded_dollar_at_argv[] = {
2703 encoded_dollar_at, NULL
2704 }; /* argv list with one element: "$@" */
2705 char **vals;
2706
2707 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00002708 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002709 /* if no variable values after "in" we skip "for" */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002710 if (!pi->next->cmds[0].argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002711 break;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002712 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002713 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002714 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002715 debug_print_strings("for_list made from", vals);
2716 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002717 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002718 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002719 for_varname = pi->cmds[0].argv[0];
2720 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002721 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002722 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002723 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00002724 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002725 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002726 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002727 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002728 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002729 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002730 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002731 /* insert next value from for_lcur */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002732//TODO: does it need escaping?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002733 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2734 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002735 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002736 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002737 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002738 if (rword == RES_DONE) {
2739 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002740 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002741#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002742#if ENABLE_HUSH_CASE
2743 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002744 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002745 continue;
2746 }
2747 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002748 char **argv;
2749
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002750 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2751 break;
2752 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002753 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00002754 while (*argv) {
2755 char *pattern = expand_string_to_string(*argv);
2756 /* TODO: which FNM_xxx flags to use? */
2757 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2758 free(pattern);
2759 if (cond_code == 0) { /* match! we will execute this branch */
2760 free(case_word); /* make future "word)" stop */
2761 case_word = NULL;
2762 break;
2763 }
2764 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002765 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002766 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002767 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002768 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002769 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002770 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002771 }
2772#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002773 if (pi->num_cmds == 0)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002774 continue;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002775
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002776 /* After analyzing all keywords and conditions, we decided
2777 * to execute this pipe. NB: has to do checkjobs(NULL)
2778 * after run_pipe() to collect any background children,
2779 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002780 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002781 {
2782 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002783#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00002784 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002785#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002786 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2787 if (r != -1) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002788 /* we only ran a builtin: rcode is already known
2789 * and we don't need to wait for anything. */
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002790#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002791 /* was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002792 if (G.flag_break_continue) {
2793 smallint fbc = G.flag_break_continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002794 /* we might fall into outer *loop*,
2795 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002796 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002797 G.depth_break_continue--;
2798 if (G.depth_break_continue == 0)
2799 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002800 /* else: e.g. "continue 2" should *break* once, *then* continue */
2801 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002802 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002803 goto check_jobs_and_break;
2804 /* "continue": simulate end of loop */
2805 rword = RES_DONE;
2806 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002807 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00002808#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002809 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002810 /* what does bash do with attempts to background builtins? */
2811 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002812 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2813 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002814#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002815 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002816 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002817#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002818 rcode = 0; /* EXIT_SUCCESS */
2819 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002820#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002821 if (G.run_list_level == 1 && G.interactive_fd) {
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002822 /* waits for completion, then fg's main shell */
2823 rcode = checkjobs_and_fg_shell(pi);
2824 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2825 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002826#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002827 { /* this one just waits for completion */
2828 rcode = checkjobs(pi);
2829 debug_printf_exec(": checkjobs returned %d\n", rcode);
2830 }
Eric Andersen25f27032001-04-26 23:22:31 +00002831 }
2832 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002833 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko87a86552008-07-29 19:43:10 +00002834 G.last_return_code = rcode;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002835
2836 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00002837#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002838 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002839 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002840#endif
2841#if ENABLE_HUSH_LOOPS
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002842 if (rword == RES_WHILE) {
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002843 if (rcode) {
2844 rcode = 0; /* "while false; do...done" - exitcode 0 */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002845 goto check_jobs_and_break;
Denis Vlasenko918a34b2008-07-28 23:17:31 +00002846 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002847 }
2848 if (rword == RES_UNTIL) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00002849 if (!rcode) {
2850 check_jobs_and_break:
2851 checkjobs(NULL);
2852 break;
2853 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002854 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002855#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00002856 if ((rcode == 0 && pi->followup == PIPE_OR)
2857 || (rcode != 0 && pi->followup == PIPE_AND)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002858 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002859 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002860 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002861 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002862 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002863
2864#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00002865 if (G.ctrl_z_flag) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002866 /* ctrl-Z forked somewhere in the past, we are the child,
2867 * and now we completed running the list. Exit. */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00002868//TODO: _exit?
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002869 exit(rcode);
2870 }
2871 ret:
Denis Vlasenko87a86552008-07-29 19:43:10 +00002872 if (!--G.run_list_level && G.interactive_fd) {
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002873 signal(SIGTSTP, SIG_IGN);
2874 signal(SIGINT, SIG_IGN);
2875 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002876#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00002877 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002878#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00002879 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00002880 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00002881 free(for_list);
2882#endif
2883#if ENABLE_HUSH_CASE
2884 free(case_word);
2885#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002886 return rcode;
2887}
2888
Eric Andersen25f27032001-04-26 23:22:31 +00002889/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002890static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002891{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002892 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002893 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00002894 if (!G.fake_mode) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002895 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00002896 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002897 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002898 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002899 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002900 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002901 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002902 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002903 return rcode;
2904}
2905
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002906
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002907/* Peek ahead in the in_str to find out if we have a "&n" construct,
2908 * as in "2>&1", that represents duplicating a file descriptor.
2909 * Return either -2 (syntax error), -1 (no &), or the number found.
2910 */
2911static int redirect_dup_num(struct in_str *input)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002912{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002913 int ch, d = 0, ok = 0;
2914 ch = i_peek(input);
2915 if (ch != '&') return -1;
2916
2917 i_getch(input); /* get the & */
2918 ch = i_peek(input);
2919 if (ch == '-') {
2920 i_getch(input);
2921 return -3; /* "-" represents "close me" */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002922 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002923 while (isdigit(ch)) {
2924 d = d*10 + (ch-'0');
2925 ok = 1;
2926 i_getch(input);
2927 ch = i_peek(input);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002928 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002929 if (ok) return d;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002930
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002931 bb_error_msg("ambiguous redirect");
2932 return -2;
Eric Andersen78a7c992001-05-15 16:30:25 +00002933}
2934
Denis Vlasenkoff182a32008-07-05 20:29:59 +00002935/* The src parameter allows us to peek forward to a possible &n syntax
Eric Andersen25f27032001-04-26 23:22:31 +00002936 * for file descriptor duplication, e.g., "2>&1".
2937 * Return code is 0 normally, 1 if a syntax error is detected in src.
2938 * Resource errors (in xmalloc) cause the process to exit */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002939static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
Eric Andersen25f27032001-04-26 23:22:31 +00002940 struct in_str *input)
2941{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002942 struct command *command = ctx->command;
2943 struct redir_struct *redir = command->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002944 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002945
2946 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002947 while (redir) {
2948 last_redir = redir;
2949 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002950 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002951 redir = xzalloc(sizeof(struct redir_struct));
2952 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002953 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002954 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002955 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002956 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002957 command->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002958 }
2959
Denis Vlasenko55789c62008-06-18 16:30:42 +00002960 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002961 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002962
2963 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2964
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002965 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002966 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002967 if (redir->dup == -2)
2968 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002969 if (redir->dup != -1) {
2970 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002971 * is legit; I postpone that to "run time"
2972 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002973 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2974 } else {
2975 /* We do _not_ try to open the file that src points to,
2976 * since we need to return and let src be expanded first.
2977 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002978 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002979 ctx->pending_redirect = redir;
2980 }
2981 return 0;
2982}
2983
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002984
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002985static struct pipe *new_pipe(void)
2986{
Eric Andersen25f27032001-04-26 23:22:31 +00002987 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002988 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002989 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002990 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002991 return pi;
2992}
2993
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002994/* Command (member of a pipe) is complete. The only possible error here
2995 * is out of memory, in which case xmalloc exits. */
2996static int done_command(struct parse_context *ctx)
2997{
2998 /* The command is really already in the pipe structure, so
2999 * advance the pipe counter and make a new, null command. */
3000 struct pipe *pi = ctx->pipe;
3001 struct command *command = ctx->command;
3002
3003 if (command) {
3004 if (command->group == NULL
3005 && command->argv == NULL
3006 && command->redirects == NULL
3007 ) {
3008 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3009 return pi->num_cmds;
3010 }
3011 pi->num_cmds++;
3012 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3013 } else {
3014 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3015 }
3016
3017 /* Only real trickiness here is that the uncommitted
3018 * command structure is not counted in pi->num_cmds. */
3019 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3020 command = &pi->cmds[pi->num_cmds];
3021 memset(command, 0, sizeof(*command));
3022
3023 ctx->command = command;
3024 /* but ctx->pipe and ctx->list_head remain unchanged */
3025
3026 return pi->num_cmds; /* used only for 0/nonzero check */
3027}
3028
3029static void done_pipe(struct parse_context *ctx, pipe_style type)
3030{
3031 int not_null;
3032
3033 debug_printf_parse("done_pipe entered, followup %d\n", type);
3034 /* Close previous command */
3035 not_null = done_command(ctx);
3036 ctx->pipe->followup = type;
3037 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3038 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3039 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3040
3041 /* Without this check, even just <enter> on command line generates
3042 * tree of three NOPs (!). Which is harmless but annoying.
3043 * IOW: it is safe to do it unconditionally.
3044 * RES_NONE case is for "for a in; do ..." (empty IN set)
3045 * to work, possibly other cases too. */
3046 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3047 struct pipe *new_p;
3048 debug_printf_parse("done_pipe: adding new pipe: "
3049 "not_null:%d ctx->ctx_res_w:%d\n",
3050 not_null, ctx->ctx_res_w);
3051 new_p = new_pipe();
3052 ctx->pipe->next = new_p;
3053 ctx->pipe = new_p;
3054 ctx->command = NULL; /* needed! */
3055 /* RES_THEN, RES_DO etc are "sticky" -
3056 * they remain set for commands inside if/while.
3057 * This is used to control execution.
3058 * RES_FOR and RES_IN are NOT sticky (needed to support
3059 * cases where variable or value happens to match a keyword):
3060 */
3061#if ENABLE_HUSH_LOOPS
3062 if (ctx->ctx_res_w == RES_FOR
3063 || ctx->ctx_res_w == RES_IN)
3064 ctx->ctx_res_w = RES_NONE;
3065#endif
3066#if ENABLE_HUSH_CASE
3067 if (ctx->ctx_res_w == RES_MATCH)
3068 ctx->ctx_res_w = RES_CASEI;
3069#endif
3070 /* Create the memory for command, roughly:
3071 * ctx->pipe->cmds = new struct command;
3072 * ctx->command = &ctx->pipe->cmds[0];
3073 */
3074 done_command(ctx);
3075 }
3076 debug_printf_parse("done_pipe return\n");
3077}
3078
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003079static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003080{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003081 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003082 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003083 /* Create the memory for command, roughly:
3084 * ctx->pipe->cmds = new struct command;
3085 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003086 */
3087 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003088}
3089
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003090
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003091/* If a reserved word is found and processed, parse context is modified
3092 * and 1 is returned.
3093 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00003094 * case, function, and select are obnoxious, save those for later.
3095 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003096#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003097struct reserved_combo {
3098 char literal[6];
3099 unsigned char res;
3100 unsigned char assignment_flag;
3101 int flag;
3102};
3103enum {
3104 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003105#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003106 FLAG_IF = (1 << RES_IF ),
3107 FLAG_THEN = (1 << RES_THEN ),
3108 FLAG_ELIF = (1 << RES_ELIF ),
3109 FLAG_ELSE = (1 << RES_ELSE ),
3110 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003111#endif
3112#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003113 FLAG_FOR = (1 << RES_FOR ),
3114 FLAG_WHILE = (1 << RES_WHILE),
3115 FLAG_UNTIL = (1 << RES_UNTIL),
3116 FLAG_DO = (1 << RES_DO ),
3117 FLAG_DONE = (1 << RES_DONE ),
3118 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003119#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003120#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003121 FLAG_MATCH = (1 << RES_MATCH),
3122 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003123#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003124 FLAG_START = (1 << RES_XXXX ),
3125};
3126
3127static const struct reserved_combo* match_reserved_word(o_string *word)
3128{
Eric Andersen25f27032001-04-26 23:22:31 +00003129 /* Mostly a list of accepted follow-up reserved words.
3130 * FLAG_END means we are done with the sequence, and are ready
3131 * to turn the compound list into a command.
3132 * FLAG_START means the word must start a new compound list.
3133 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003134 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003135#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003136 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3137 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3138 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3139 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3140 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3141 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003142#endif
3143#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003144 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3145 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3146 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3147 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3148 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3149 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003150#endif
3151#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003152 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3153 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003154#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003155 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003156 const struct reserved_combo *r;
3157
3158 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3159 if (strcmp(word->data, r->literal) == 0)
3160 return r;
3161 }
3162 return NULL;
3163}
3164static int reserved_word(o_string *word, struct parse_context *ctx)
3165{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003166#if ENABLE_HUSH_CASE
3167 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003168 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003169 };
3170#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003171 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003172
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003173 r = match_reserved_word(word);
3174 if (!r)
3175 return 0;
3176
3177 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003178#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003179 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3180 /* "case word IN ..." - IN part starts first match part */
3181 r = &reserved_match;
3182 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003183#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003184 if (r->flag == 0) { /* '!' */
3185 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003186 syntax(NULL);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003187 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003188 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003189 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003190 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003191 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003192 if (r->flag & FLAG_START) {
3193 struct parse_context *new;
3194 debug_printf("push stack\n");
3195 new = xmalloc(sizeof(*new));
3196 *new = *ctx; /* physical copy */
3197 initialize_context(ctx);
3198 ctx->stack = new;
3199 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3200 syntax(NULL);
3201 ctx->ctx_res_w = RES_SNTX;
3202 return 1;
3203 }
3204 ctx->ctx_res_w = r->res;
3205 ctx->old_flag = r->flag;
3206 if (ctx->old_flag & FLAG_END) {
3207 struct parse_context *old;
3208 debug_printf("pop stack\n");
3209 done_pipe(ctx, PIPE_SEQ);
3210 old = ctx->stack;
3211 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003212 old->command->grp_type = GRP_NORMAL;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003213 *ctx = *old; /* physical copy */
3214 free(old);
3215 }
3216 word->o_assignment = r->assignment_flag;
3217 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003218}
Denis Vlasenko06810332007-05-21 23:30:54 +00003219#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003220
Denis Vlasenkoddc8ae32008-10-14 12:50:34 +00003221//TODO: many, many callers don't check error from done_word()
3222
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003223/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003224 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003225static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003226{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003227 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003228
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003229 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003230 if (word->length == 0 && word->nonnull == 0) {
3231 debug_printf_parse("done_word return 0: true null, ignored\n");
3232 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003233 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003234 /* If this word wasn't an assignment, next ones definitely
3235 * can't be assignments. Even if they look like ones. */
3236 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3237 && word->o_assignment != WORD_IS_KEYWORD
3238 ) {
3239 word->o_assignment = NOT_ASSIGNMENT;
3240 } else {
3241 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003242 command->assignment_cnt++;
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003243 word->o_assignment = MAYBE_ASSIGNMENT;
3244 }
3245
Eric Andersen25f27032001-04-26 23:22:31 +00003246 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003247 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3248 * only if run as "bash", not "sh" */
3249 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003250 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003251 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003252 } else {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003253 /* "{ echo foo; } echo bar" - bad */
3254 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003255 if (command->group) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003256 syntax(NULL);
3257 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3258 return 1;
3259 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003260#if HAS_KEYWORDS
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003261#if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00003262 if (ctx->ctx_dsemicolon
3263 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3264 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00003265 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003266 /* ctx->ctx_res_w = RES_MATCH; */
3267 ctx->ctx_dsemicolon = 0;
3268 } else
3269#endif
3270
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003271 if (!command->argv /* if it's the first word... */
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003272#if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003273 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3274 && ctx->ctx_res_w != RES_IN
Denis Vlasenko6bdff082008-07-09 20:14:53 +00003275#endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003276 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003277 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3278 if (reserved_word(word, ctx)) {
3279 o_reset(word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003280 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3281 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003282 }
Eric Andersen25f27032001-04-26 23:22:31 +00003283 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003284#endif
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003285 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003286 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3287 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003288 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003289 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003290 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003291 char *p = word->data;
3292 while (p[0] == SPECIAL_VAR_SYMBOL
3293 && (p[1] & 0x7f) == '@'
3294 && p[2] == SPECIAL_VAR_SYMBOL
3295 ) {
3296 p += 3;
3297 }
3298 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003299 /* saw no "$@", or not only "$@" but some
3300 * real text is there too */
3301 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00003302 * e.g. "", $empty"" etc to not disappear */
3303 o_addchr(word, SPECIAL_VAR_SYMBOL);
3304 o_addchr(word, SPECIAL_VAR_SYMBOL);
3305 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003306 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003307 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003308 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003309 }
Eric Andersen25f27032001-04-26 23:22:31 +00003310
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003311 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003312 ctx->pending_redirect = NULL;
3313
Denis Vlasenko06810332007-05-21 23:30:54 +00003314#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003315 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003316 /* NB: basically, this makes hush see "for v in ..." syntax as if
3317 * as it is "for v; in ...". FOR and IN become two pipe structs
3318 * in parse tree. */
3319 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003320//TODO: check that command->argv[0] is a valid variable name!
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003321 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003322 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003323#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003324#if ENABLE_HUSH_CASE
3325 /* Force CASE to have just one word */
3326 if (ctx->ctx_res_w == RES_CASE) {
3327 done_pipe(ctx, PIPE_SEQ);
3328 }
3329#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003330 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003331 return 0;
3332}
3333
Eric Andersen25f27032001-04-26 23:22:31 +00003334/* If a redirect is immediately preceded by a number, that number is
3335 * supposed to tell which file descriptor to redirect. This routine
3336 * looks for such preceding numbers. In an ideal world this routine
3337 * needs to handle all the following classes of redirects...
3338 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3339 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3340 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3341 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3342 * A -1 output from this program means no valid number was found, so the
3343 * caller should use the appropriate default for this redirection.
3344 */
3345static int redirect_opt_num(o_string *o)
3346{
3347 int num;
3348
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003349 if (o->length == 0)
3350 return -1;
3351 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003352 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003353 return -1;
3354 }
3355 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003356 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003357 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003358 return num;
3359}
3360
Mike Frysingerddbee972009-03-22 22:48:41 +00003361static int parse_stream(o_string *dest, struct parse_context *ctx,
3362 struct in_str *input0, const char *end_trigger);
3363
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003364#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003365static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003366{
3367 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003368 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003369
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003370 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003371/* *** NOMMU WARNING *** */
3372/* By using vfork here, we suspend parent till child exits or execs.
3373 * If child will not do it before it fills the pipe, it can block forever
3374 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003375 * Try this script:
3376 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3377 * huge=`cat TESTFILE` # will block here forever
3378 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003379 */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003380 pid = BB_MMU ? fork() : vfork();
3381 if (pid < 0)
3382 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenko05743d72008-02-10 12:10:08 +00003383 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003384 if (ENABLE_HUSH_JOB)
3385 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003386 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003387 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003388 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003389#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003390 G.run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003391#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003392 /* Process substitution is not considered to be usual
3393 * 'command execution'.
3394 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3395 /* Not needed, we are relying on it being disabled
3396 * everywhere outside actual command execution. */
3397 /*set_jobctrl_sighandler(SIG_IGN);*/
3398 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003399 /* Freeing 'head' here would break NOMMU. */
3400 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003401 }
Eric Andersen25f27032001-04-26 23:22:31 +00003402 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003403 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003404 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003405 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003406}
3407
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003408/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003409static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003410 struct in_str *input,
3411 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003412{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003413 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003414 o_string result = NULL_O_STRING;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003415 struct parse_context inner;
Eric Andersen25f27032001-04-26 23:22:31 +00003416 FILE *p;
3417 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003418
Eric Andersen25f27032001-04-26 23:22:31 +00003419 initialize_context(&inner);
3420
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003421 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003422 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003423 if (retcode != 0)
3424 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003425 done_word(&result, &inner);
3426 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003427 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003428
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003429 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003430 if (p == NULL)
3431 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003432 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003433 setup_file_in_str(&pipe_str, p);
3434
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003435 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003436 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003437 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003438 if (ch == '\n') {
3439 eol_cnt++;
3440 continue;
3441 }
3442 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003443 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003444 eol_cnt--;
3445 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003446 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003447 }
3448
3449 debug_printf("done reading from pipe, pclose()ing\n");
3450 /* This is the step that wait()s for the child. Should be pretty
3451 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003452 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003453 * at the same time. That would be a lot of work, and contrary
3454 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003455 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003456 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003457 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003458 return retcode;
3459}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003460#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003461
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003462static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00003463 struct in_str *input, int ch)
3464{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003465 /* dest contains characters seen prior to ( or {.
3466 * Typically it's empty, but for functions defs,
3467 * it contains function name (without '()'). */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003468 int rcode;
3469 const char *endch = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003470 struct parse_context sub;
3471 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003472
3473 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003474#if ENABLE_HUSH_FUNCTIONS
3475 if (ch == 'F') { /* function definition? */
3476 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3477 //command->fname = dest->data;
3478 command->grp_type = GRP_FUNCTION;
3479//TODO: review every o_reset() location... do they handle all o_string fields correctly?
3480 memset(dest, 0, sizeof(*dest));
3481 }
3482#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003483 if (command->argv /* word [word](... */
3484 || dest->length /* word(... */
3485 || dest->nonnull /* ""(... */
3486 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003487 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003488 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3489 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003490 }
3491 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003492 endch = "}";
3493 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003494 endch = ")";
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003495 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00003496 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003497 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003498 if (rcode == 0) {
3499 done_word(dest, &sub); /* finish off the final word in the subcontext */
3500 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003501 command->group = sub.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003502 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003503 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003504 return rcode;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003505 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00003506}
3507
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003508#if ENABLE_HUSH_TICK
3509/* Subroutines for copying $(...) and `...` things */
3510static void add_till_backquote(o_string *dest, struct in_str *input);
3511/* '...' */
3512static void add_till_single_quote(o_string *dest, struct in_str *input)
3513{
3514 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003515 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003516 if (ch == EOF)
3517 break;
3518 if (ch == '\'')
3519 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003520 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003521 }
3522}
3523/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3524static void add_till_double_quote(o_string *dest, struct in_str *input)
3525{
3526 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003527 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003528 if (ch == '"')
3529 break;
3530 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003531 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003532 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003533 }
3534 if (ch == EOF)
3535 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003536 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003537 if (ch == '`') {
3538 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003539 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003540 continue;
3541 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003542 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003543 }
3544}
3545/* Process `cmd` - copy contents until "`" is seen. Complicated by
3546 * \` quoting.
3547 * "Within the backquoted style of command substitution, backslash
3548 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3549 * The search for the matching backquote shall be satisfied by the first
3550 * backquote found without a preceding backslash; during this search,
3551 * if a non-escaped backquote is encountered within a shell comment,
3552 * a here-document, an embedded command substitution of the $(command)
3553 * form, or a quoted string, undefined results occur. A single-quoted
3554 * or double-quoted string that begins, but does not end, within the
3555 * "`...`" sequence produces undefined results."
3556 * Example Output
3557 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3558 */
3559static void add_till_backquote(o_string *dest, struct in_str *input)
3560{
3561 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003562 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003563 if (ch == '`')
3564 break;
3565 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003566 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003567 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003568 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003569 ch = ch2;
3570 }
3571 if (ch == EOF)
3572 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003573 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003574 }
3575}
3576/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3577 * quoting and nested ()s.
3578 * "With the $(command) style of command substitution, all characters
3579 * following the open parenthesis to the matching closing parenthesis
3580 * constitute the command. Any valid shell script can be used for command,
3581 * except a script consisting solely of redirections which produces
3582 * unspecified results."
3583 * Example Output
3584 * echo $(echo '(TEST)' BEST) (TEST) BEST
3585 * echo $(echo 'TEST)' BEST) TEST) BEST
3586 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3587 */
3588static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3589{
3590 int count = 0;
3591 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003592 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003593 if (ch == EOF)
3594 break;
3595 if (ch == '(')
3596 count++;
3597 if (ch == ')')
3598 if (--count < 0)
3599 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003600 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003601 if (ch == '\'') {
3602 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003603 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003604 continue;
3605 }
3606 if (ch == '"') {
3607 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003608 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003609 continue;
3610 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003611 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3612 ch = i_getch(input);
3613 if (ch == EOF)
3614 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003615 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003616 continue;
3617 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003618 }
3619}
3620#endif /* ENABLE_HUSH_TICK */
3621
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003622/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003623static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003624{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003625 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003626 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003627
3628 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003629 if (isalpha(ch)) {
Denis Vlasenkod4981312008-07-31 10:34:48 +00003630 i_getch(input);
3631 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003632 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003633 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003634 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003635 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003636 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003637 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003638 if (!isalnum(ch) && ch != '_')
3639 break;
Denis Vlasenkod4981312008-07-31 10:34:48 +00003640 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003641 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003642 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003643 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003644 make_one_char_var:
Denis Vlasenkod4981312008-07-31 10:34:48 +00003645 i_getch(input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003646 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003647 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003648 o_addchr(dest, ch | quote_mask);
3649 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003650 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003651 case '$': /* pid */
3652 case '!': /* last bg pid */
3653 case '?': /* last exit code */
3654 case '#': /* number of args */
3655 case '*': /* args */
3656 case '@': /* args */
3657 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003658 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003659 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3660 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003661 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003662 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003663 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003664 if (ch == '}')
3665 break;
3666 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003667 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003668 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3669 return 1;
3670 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003671 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003672 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003673 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003674 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003675 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003676 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003677#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003678 case '(': {
3679 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003680 i_getch(input);
3681 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3682 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003683 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003684 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003686 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003687 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003688#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003689 case '_':
Denis Vlasenkod4981312008-07-31 10:34:48 +00003690 i_getch(input);
3691 ch = i_peek(input);
3692 if (isalnum(ch)) { /* it's $_name or $_123 */
3693 ch = '_';
3694 goto make_var;
3695 }
3696 /* else: it's $_ */
3697 case '-':
Eric Andersen25f27032001-04-26 23:22:31 +00003698 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003699 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003700 return 1;
3701 break;
3702 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003703 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003704 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003705 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003706 return 0;
3707}
3708
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003709/* Scan input, call done_word() whenever full IFS delimited word was seen.
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003710 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3711 * Return code is 0 if end_trigger char is met,
3712 * -1 on EOF (but if end_trigger == NULL then return 0),
Denis Vlasenko55789c62008-06-18 16:30:42 +00003713 * 1 for syntax error */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003714static int parse_stream(o_string *dest, struct parse_context *ctx,
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003715 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003716{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003717 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003718 int redir_fd;
3719 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003720 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003721 int next;
3722
Denis Vlasenkoff097622007-10-01 10:00:45 +00003723 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003724 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003725 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003726
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003727 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 +00003728
Denis Vlasenko1a735862007-05-23 00:32:25 +00003729 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003730 m = CHAR_IFS;
3731 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003732 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003733 if (ch != EOF) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003734 m = G.charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003735 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003736 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003737 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003738 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003739 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003740 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003741 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003742 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003743 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003744 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003745 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003746 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3747 return 1;
3748 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003749 o_addQchr(dest, ch);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003750 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3751 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00003752 && ch == '='
3753 && is_assignment(dest->data)
3754 ) {
3755 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3756 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003757 continue;
3758 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003759 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003760 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003761 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003762 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003763 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003764 if (ch == EOF)
3765 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003766 /* If we aren't performing a substitution, treat
3767 * a newline as a command separator.
3768 * [why we don't handle it exactly like ';'? --vda] */
3769 if (end_trigger && ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00003770#if ENABLE_HUSH_CASE
3771 /* "case ... in <newline> word) ..." -
3772 * newlines are ignored (but ';' wouldn't be) */
3773 if (dest->length == 0 // && argv[0] == NULL
3774 && ctx->ctx_res_w == RES_MATCH
3775 ) {
3776 continue;
3777 }
3778#endif
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003779 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003780 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003781 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003782 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003783 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003784 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003785 /* Special case: (...word) makes last word terminate,
3786 * as if ';' is seen */
3787 if (ch == ')') {
3788 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003789//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003790 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003791 dest->o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003792 }
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00003793 if (!HAS_KEYWORDS
3794 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3795 ) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003796 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3797 return 0;
3798 }
3799 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003800 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003801 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003802 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003803
3804 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3805 /* ch is a special char and thus this word
3806 * cannot be an assignment: */
3807 dest->o_assignment = NOT_ASSIGNMENT;
3808 }
3809
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003810 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003811 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003812 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003813 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003814 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003815 if (ch == EOF || ch == '\n')
3816 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003817 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003818 }
Eric Andersen25f27032001-04-26 23:22:31 +00003819 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003820 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003821 }
3822 break;
3823 case '\\':
3824 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003825 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003826 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003827 return 1;
3828 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003829 /* bash:
3830 * "The backslash retains its special meaning [in "..."]
3831 * only when followed by one of the following characters:
3832 * $, `, ", \, or <newline>. A double quote may be quoted
3833 * within double quotes by preceding it with a backslash.
3834 * If enabled, history expansion will be performed unless
3835 * an ! appearing in double quotes is escaped using
3836 * a backslash. The backslash preceding the ! is not removed."
3837 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003838 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003839 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003840 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003841 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003842 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003843 }
3844 } else {
3845 o_addchr(dest, '\\');
3846 o_addchr(dest, i_getch(input));
3847 }
Eric Andersen25f27032001-04-26 23:22:31 +00003848 break;
3849 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003850 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003851 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3852 return 1;
3853 }
Eric Andersen25f27032001-04-26 23:22:31 +00003854 break;
3855 case '\'':
3856 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003857 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003858 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003859 if (ch == EOF) {
3860 syntax("unterminated '");
3861 debug_printf_parse("parse_stream return 1: unterminated '\n");
3862 return 1;
3863 }
3864 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003865 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003866 if (dest->o_assignment == NOT_ASSIGNMENT)
3867 o_addqchr(dest, ch);
3868 else
3869 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003870 }
Eric Andersen25f27032001-04-26 23:22:31 +00003871 break;
3872 case '"':
3873 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003874 shadow_quote ^= 1; /* invert */
3875 if (dest->o_assignment == NOT_ASSIGNMENT)
3876 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003877 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003878#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003879 case '`': {
3880 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003881 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003882 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003883 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003885 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003886 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003887 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003888#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003889 case '>':
3890 redir_fd = redirect_opt_num(dest);
3891 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003892 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003893 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003894 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003895 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003896 }
3897#if 0
3898 else if (next == '(') {
3899 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003900 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003901 return 1;
3902 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003903#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003904 setup_redirect(ctx, redir_fd, redir_style, input);
3905 break;
3906 case '<':
3907 redir_fd = redirect_opt_num(dest);
3908 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003909 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003910 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003911 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003912 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003913 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003914 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003915 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003916 }
3917#if 0
3918 else if (next == '(') {
3919 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003920 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003921 return 1;
3922 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003923#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003924 setup_redirect(ctx, redir_fd, redir_style, input);
3925 break;
3926 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003927#if ENABLE_HUSH_CASE
3928 case_semi:
3929#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003930 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003931 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003932#if ENABLE_HUSH_CASE
3933 /* Eat multiple semicolons, detect
3934 * whether it means something special */
3935 while (1) {
3936 ch = i_peek(input);
3937 if (ch != ';')
3938 break;
3939 i_getch(input);
3940 if (ctx->ctx_res_w == RES_CASEI) {
3941 ctx->ctx_dsemicolon = 1;
3942 ctx->ctx_res_w = RES_MATCH;
3943 break;
3944 }
3945 }
3946#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003947 new_cmd:
3948 /* We just finished a cmd. New one may start
3949 * with an assignment */
3950 dest->o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00003951 break;
3952 case '&':
3953 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003954 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003955 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003956 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003957 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003958 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003959 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003960 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00003961 case '|':
3962 done_word(dest, ctx);
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003963#if ENABLE_HUSH_CASE
3964 if (ctx->ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00003965 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003966#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003967 if (next == '|') { /* || */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003968 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003969 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003970 } else {
3971 /* we could pick up a file descriptor choice here
3972 * with redirect_opt_num(), but bash doesn't do it.
3973 * "echo foo 2| cat" yields "foo 2". */
3974 done_command(ctx);
3975 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003976 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00003977 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003978#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00003979 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003980 if (ctx->ctx_res_w == RES_MATCH
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003981 && ctx->command->argv == NULL /* not (word|(... */
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003982 && dest->length == 0 /* not word(... */
3983 && dest->nonnull == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003984 ) {
3985 continue;
3986 }
3987#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003988#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003989 if (dest->length != 0 /* not just () but word() */
3990 && dest->nonnull == 0 /* not a"b"c() */
3991 && ctx->command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003992//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003993 && i_peek(input) == ')'
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003994 && !match_reserved_word(dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003995 ) {
3996 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003997 i_getch(input);
3998 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003999//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004000 ch = i_getch(input);
4001 } while (ch == ' ' || ch == '\n');
4002 if (ch != '{') {
4003 syntax("was expecting {");
4004 debug_printf_parse("parse_stream return 1\n");
4005 return 1;
4006 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004007 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004008 }
4009#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004010 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004011 if (parse_group(dest, ctx, input, ch) != 0) {
4012 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004013 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004014 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004015 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00004016 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004017#if ENABLE_HUSH_CASE
4018 if (ctx->ctx_res_w == RES_MATCH)
4019 goto case_semi;
4020#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004021 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00004022 /* proper use of this character is caught by end_trigger:
4023 * if we see {, we call parse_group(..., end_trigger='}')
4024 * and it will match } earlier (not here). */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004025 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004026 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004027 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004028 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004029 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004030 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004031 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004032 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004033 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004034 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004035 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00004036 return 0;
4037}
4038
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004039static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00004040{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00004041 while (*set)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004042 G.charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00004043}
4044
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004045static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00004046{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004047 G.ifs = getenv("IFS");
4048 if (G.ifs == NULL)
4049 G.ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00004050 /* Precompute a list of 'flow through' behavior so it can be treated
4051 * quickly up front. Computation is necessary because of IFS.
4052 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004053 * The charmap[] array only really needs two bits each,
4054 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00004055 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004056 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004057#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004058 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004059#else
4060 set_in_charmap("\\$\"", CHAR_SPECIAL);
4061#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004062 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004063 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00004064}
4065
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004066/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00004067 * from builtin_source() and builtin_eval() */
4068static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004069{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004070 struct parse_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004071 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00004072 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004073
Eric Andersen25f27032001-04-26 23:22:31 +00004074 do {
4075 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00004076 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004077#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00004078 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004079#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004080 /* We will stop & execute after each ';' or '\n'.
4081 * Example: "sleep 9999; echo TEST" + ctrl-C:
4082 * TEST should be printed */
Denis Vlasenko2b576b82008-08-04 00:46:07 +00004083 temp.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004084 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004085#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004086 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004087 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004088 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004089#endif
4090 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004091 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004092 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00004093 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004094 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4095 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004096 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004097 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004098#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004099 if (ctx.old_flag != 0) {
4100 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004101 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004102 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004103#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004104 /*temp.nonnull = 0; - o_free does it below */
4105 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00004106 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004107 /* Discard all unprocessed line input, force prompt on */
4108 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004109#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004110 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004111#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00004112 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004113 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004114 /* loop on syntax errors, return on EOF: */
4115 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00004116 return 0;
4117}
4118
Denis Vlasenko170435c2007-05-23 13:01:10 +00004119static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00004120{
4121 struct in_str input;
4122 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00004123 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00004124}
4125
Denis Vlasenko170435c2007-05-23 13:01:10 +00004126static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00004127{
4128 int rcode;
4129 struct in_str input;
4130 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00004131 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00004132 return rcode;
4133}
4134
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004135#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00004136/* Make sure we have a controlling tty. If we get started under a job
4137 * aware app (like bash for example), make sure we are now in charge so
4138 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00004139static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00004140{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004141 pid_t shell_pgrp;
4142
Denis Vlasenko87a86552008-07-29 19:43:10 +00004143 shell_pgrp = getpgrp();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004144 close_on_exec_on(G.interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004145
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004146 /* If we were ran as 'hush &',
4147 * sleep until we are in the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004148 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004149 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00004150 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00004151 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004152 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00004153
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004154 /* Ignore job-control and misc signals. */
4155 set_jobctrl_sighandler(SIG_IGN);
4156 set_misc_sighandler(SIG_IGN);
4157//huh? signal(SIGCHLD, SIG_IGN);
4158
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00004159 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004160 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00004161
4162 /* Put ourselves in our own process group. */
Bernhard Reutner-Fischer864329d2008-09-25 10:55:05 +00004163 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00004164 /* Grab control of the terminal. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004165 tcsetpgrp(G.interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00004166}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004167#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00004168
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004169
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00004170int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00004171int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00004172{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004173 static const struct variable const_shell_ver = {
4174 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004175 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004176 .max_len = 1, /* 0 can provoke free(name) */
4177 .flg_export = 1,
4178 .flg_read_only = 1,
4179 };
4180
Eric Andersen25f27032001-04-26 23:22:31 +00004181 int opt;
4182 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004183 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004184 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00004185
Denis Vlasenko574f2f42008-02-27 18:41:59 +00004186 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004187
Denis Vlasenko87a86552008-07-29 19:43:10 +00004188 G.root_pid = getpid();
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00004189
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004190 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004191 G.shell_ver = const_shell_ver; /* copying struct here */
4192 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004193 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004194 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4195 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004196 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004197 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00004198 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004199 if (e) while (*e) {
4200 char *value = strchr(*e, '=');
4201 if (value) { /* paranoia */
4202 cur_var->next = xzalloc(sizeof(*cur_var));
4203 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004204 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004205 cur_var->max_len = strlen(*e);
4206 cur_var->flg_export = 1;
4207 }
4208 e++;
4209 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004210 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00004211 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004212
Denis Vlasenko38f63192007-01-22 09:03:07 +00004213#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00004214 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00004215#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004216 /* XXX what should these be while sourcing /etc/profile? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004217 G.global_argc = argc;
4218 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00004219 /* Initialize some more globals to non-zero values */
4220 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004221#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00004222 if (ENABLE_FEATURE_EDITING)
4223 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00004224 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004225#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00004226
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004227 if (EXIT_SUCCESS) /* otherwise is already done */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004228 G.last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00004229
4230 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004231 debug_printf("sourcing /etc/profile\n");
Denis Vlasenko5415c852008-07-21 23:05:26 +00004232 input = fopen_for_read("/etc/profile");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00004233 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00004234 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00004235 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00004236 fclose(input);
4237 }
Eric Andersen25f27032001-04-26 23:22:31 +00004238 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004239 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004240
Eric Andersen25f27032001-04-26 23:22:31 +00004241 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4242 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004243 case 'c':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004244 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00004245 if (!argv[optind]) {
4246 /* -c 'script' (no params): prevent empty $0 */
4247 *--G.global_argv = argv[0];
4248 optind--;
4249 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004250 G.global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00004251 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004252 goto final_return;
4253 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00004254 /* Well, we cannot just declare interactiveness,
4255 * we have to have some stuff (ctty, etc) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004256 /* G.interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004257 break;
4258 case 'f':
Denis Vlasenko87a86552008-07-29 19:43:10 +00004259 G.fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004260 break;
4261 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004262#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004263 fprintf(stderr, "Usage: sh [FILE]...\n"
4264 " or: sh -c command [args]...\n\n");
4265 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004266#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004267 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00004268#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004269 }
4270 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004271#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004272 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00004273 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00004274 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00004275 * no arguments remaining or the -s flag given
4276 * standard input is a terminal
4277 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004278 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004279 if (argv[optind] == NULL && input == stdin
4280 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4281 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004282 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4283 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4284 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004285 /* try to dup to high fd#, >= 255 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004286 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4287 if (G.interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004288 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004289 G.interactive_fd = dup(STDIN_FILENO);
4290 if (G.interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004291 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004292 G.interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004293 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00004294 // TODO: track & disallow any attempts of user
4295 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004296 }
Eric Andersen25f27032001-04-26 23:22:31 +00004297 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004298 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4299 if (G.interactive_fd) {
4300 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00004301 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00004302 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00004303 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00004304 * (we reset die_sleep = 0 whereever we [v]fork) */
4305 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00004306 if (setjmp(die_jmp)) {
4307 /* xfunc has failed! die die die */
4308 hush_exit(xfunc_error_retval);
4309 }
Eric Andersenada18ff2001-05-21 16:18:22 +00004310 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004311#elif ENABLE_HUSH_INTERACTIVE
4312/* no job control compiled, only prompt/line editing */
4313 if (argv[optind] == NULL && input == stdin
4314 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4315 ) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004316 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4317 if (G.interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004318 /* try to dup to any fd */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004319 G.interactive_fd = dup(STDIN_FILENO);
4320 if (G.interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004321 /* give up */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004322 G.interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004323 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004324 if (G.interactive_fd) {
4325 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00004326 set_misc_sighandler(SIG_IGN);
4327 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00004328 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00004329#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00004330
Mike Frysingerb2705e12009-03-23 08:44:02 +00004331 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G.interactive_fd) {
4332 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4333 printf("Enter 'help' for a list of built-in commands.\n\n");
4334 }
4335
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004336 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00004337 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004338 } else {
4339 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004340 G.global_argv = argv + optind;
4341 G.global_argc = argc - optind;
Denis Vlasenko5415c852008-07-21 23:05:26 +00004342 input = xfopen_for_read(argv[optind]);
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00004343 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00004344 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00004345 }
Eric Andersen25f27032001-04-26 23:22:31 +00004346
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004347 final_return:
4348
Denis Vlasenko38f63192007-01-22 09:03:07 +00004349#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00004350 fclose(input);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004351 if (G.cwd != bb_msg_unknown)
4352 free((char*)G.cwd);
4353 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004354 while (cur_var) {
4355 struct variable *tmp = cur_var;
4356 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00004357 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00004358 cur_var = cur_var->next;
4359 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00004360 }
Eric Andersen25f27032001-04-26 23:22:31 +00004361#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00004362 hush_exit(opt ? opt : G.last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00004363}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00004364
4365
4366#if ENABLE_LASH
4367int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4368int lash_main(int argc, char **argv)
4369{
4370 //bb_error_msg("lash is deprecated, please use hush instead");
4371 return hush_main(argc, argv);
4372}
4373#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004374
4375
4376/*
4377 * Built-ins
4378 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004379static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004380{
4381 return 0;
4382}
4383
4384static int builtin_test(char **argv)
4385{
4386 int argc = 0;
4387 while (*argv) {
4388 argc++;
4389 argv++;
4390 }
4391 return test_main(argc, argv - argc);
4392}
4393
4394static int builtin_echo(char **argv)
4395{
4396 int argc = 0;
4397 while (*argv) {
4398 argc++;
4399 argv++;
4400 }
4401 return echo_main(argc, argv - argc);
4402}
4403
4404static int builtin_eval(char **argv)
4405{
4406 int rcode = EXIT_SUCCESS;
4407
4408 if (argv[1]) {
4409 char *str = expand_strvec_to_string(argv + 1);
4410 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4411 free(str);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004412 rcode = G.last_return_code;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004413 }
4414 return rcode;
4415}
4416
4417static int builtin_cd(char **argv)
4418{
4419 const char *newdir;
4420 if (argv[1] == NULL) {
4421 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4422 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4423 newdir = getenv("HOME") ? : "/";
4424 } else
4425 newdir = argv[1];
4426 if (chdir(newdir)) {
4427 printf("cd: %s: %s\n", newdir, strerror(errno));
4428 return EXIT_FAILURE;
4429 }
4430 set_cwd();
4431 return EXIT_SUCCESS;
4432}
4433
4434static int builtin_exec(char **argv)
4435{
4436 if (argv[1] == NULL)
4437 return EXIT_SUCCESS; /* bash does this */
4438 {
4439#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004440 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004441#endif
4442// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004443 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004444 /* never returns */
4445 }
4446}
4447
4448static int builtin_exit(char **argv)
4449{
4450// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4451 //puts("exit"); /* bash does it */
4452// TODO: warn if we have background jobs: "There are stopped jobs"
4453// On second consecutive 'exit', exit anyway.
4454 if (argv[1] == NULL)
Denis Vlasenko87a86552008-07-29 19:43:10 +00004455 hush_exit(G.last_return_code);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004456 /* mimic bash: exit 123abc == exit 255 + error msg */
4457 xfunc_error_retval = 255;
4458 /* bash: exit -2 == exit 254, no error msg */
4459 hush_exit(xatoi(argv[1]) & 0xff);
4460}
4461
4462static int builtin_export(char **argv)
4463{
4464 const char *value;
4465 char *name = argv[1];
4466
4467 if (name == NULL) {
4468 // TODO:
4469 // ash emits: export VAR='VAL'
4470 // bash: declare -x VAR="VAL"
4471 // (both also escape as needed (quotes, $, etc))
4472 char **e = environ;
4473 if (e)
4474 while (*e)
4475 puts(*e++);
4476 return EXIT_SUCCESS;
4477 }
4478
4479 value = strchr(name, '=');
4480 if (!value) {
4481 /* They are exporting something without a =VALUE */
4482 struct variable *var;
4483
4484 var = get_local_var(name);
4485 if (var) {
4486 var->flg_export = 1;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00004487 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004488 putenv(var->varstr);
4489 }
4490 /* bash does not return an error when trying to export
4491 * an undefined variable. Do likewise. */
4492 return EXIT_SUCCESS;
4493 }
4494
4495 set_local_var(xstrdup(name), 1);
4496 return EXIT_SUCCESS;
4497}
4498
4499#if ENABLE_HUSH_JOB
4500/* built-in 'fg' and 'bg' handler */
4501static int builtin_fg_bg(char **argv)
4502{
4503 int i, jobnum;
4504 struct pipe *pi;
4505
Denis Vlasenko87a86552008-07-29 19:43:10 +00004506 if (!G.interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004507 return EXIT_FAILURE;
4508 /* If they gave us no args, assume they want the last backgrounded task */
4509 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004510 for (pi = G.job_list; pi; pi = pi->next) {
4511 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004512 goto found;
4513 }
4514 }
4515 bb_error_msg("%s: no current job", argv[0]);
4516 return EXIT_FAILURE;
4517 }
4518 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4519 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4520 return EXIT_FAILURE;
4521 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004522 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004523 if (pi->jobid == jobnum) {
4524 goto found;
4525 }
4526 }
4527 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4528 return EXIT_FAILURE;
4529 found:
4530 // TODO: bash prints a string representation
4531 // of job being foregrounded (like "sleep 1 | cat")
4532 if (*argv[0] == 'f') {
4533 /* Put the job into the foreground. */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004534 tcsetpgrp(G.interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004535 }
4536
4537 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004538 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4539 for (i = 0; i < pi->num_cmds; i++) {
4540 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4541 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004542 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004543 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004544
4545 i = kill(- pi->pgrp, SIGCONT);
4546 if (i < 0) {
4547 if (errno == ESRCH) {
4548 delete_finished_bg_job(pi);
4549 return EXIT_SUCCESS;
4550 } else {
4551 bb_perror_msg("kill (SIGCONT)");
4552 }
4553 }
4554
4555 if (*argv[0] == 'f') {
4556 remove_bg_job(pi);
4557 return checkjobs_and_fg_shell(pi);
4558 }
4559 return EXIT_SUCCESS;
4560}
4561#endif
4562
4563#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004564static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004565{
4566 const struct built_in_command *x;
4567
4568 printf("\nBuilt-in commands:\n");
4569 printf("-------------------\n");
4570 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4571 printf("%s\t%s\n", x->cmd, x->descr);
4572 }
4573 printf("\n\n");
4574 return EXIT_SUCCESS;
4575}
4576#endif
4577
4578#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004579static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004580{
4581 struct pipe *job;
4582 const char *status_string;
4583
Denis Vlasenko87a86552008-07-29 19:43:10 +00004584 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004585 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004586 status_string = "Stopped";
4587 else
4588 status_string = "Running";
4589
4590 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4591 }
4592 return EXIT_SUCCESS;
4593}
4594#endif
4595
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004596static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004597{
4598 puts(set_cwd());
4599 return EXIT_SUCCESS;
4600}
4601
4602static int builtin_read(char **argv)
4603{
4604 char *string;
4605 const char *name = argv[1] ? argv[1] : "REPLY";
4606
4607 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4608 return set_local_var(string, 0);
4609}
4610
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004611/* built-in 'set' handler
4612 * SUSv3 says:
4613 * set [-abCefmnuvx] [-h] [-o option] [argument...]
4614 * set [+abCefmnuvx] [+h] [+o option] [argument...]
4615 * set -- [argument...]
4616 * set -o
4617 * set +o
4618 * Implementations shall support the options in both their hyphen and
4619 * plus-sign forms. These options can also be specified as options to sh.
4620 * Examples:
4621 * Write out all variables and their values: set
4622 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4623 * Turn on the -x and -v options: set -xv
4624 * Unset all positional parameters: set --
4625 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4626 * Set the positional parameters to the expansion of x, even if x expands
4627 * with a leading '-' or '+': set -- $x
4628 *
4629 * So far, we only support "set -- [argument...]" by ignoring all options
4630 * (also, "-o option" will be mishandled by taking "option" as parameter #1).
4631 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004632static int builtin_set(char **argv)
4633{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004634 int n;
4635 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004636 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004637
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004638 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004639 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00004640 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004641 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004642 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00004643 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004644
Denis Vlasenko424f79b2009-03-22 14:23:34 +00004645 do {
4646 if (arg[0] == '+')
4647 continue;
4648 if (arg[0] != '-')
4649 break;
4650 if (arg[1] == '-' && arg[2] == '\0') {
4651 argv++;
4652 break;
4653 }
4654 } while ((arg = *++argv) != NULL);
4655 /* Now argv[0] is 1st argument */
4656
4657 /* NB: G.global_argv[0] ($0) is never freed/changed */
4658 g_argv = G.global_argv;
4659 if (G.global_args_malloced) {
4660 pp = g_argv;
4661 while (*++pp)
4662 free(*pp);
4663 g_argv[1] = NULL;
4664 } else {
4665 G.global_args_malloced = 1;
4666 pp = xzalloc(sizeof(pp[0]) * 2);
4667 pp[0] = g_argv[0]; /* retain $0 */
4668 g_argv = pp;
4669 }
4670 /* This realloc's G.global_argv */
4671 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4672
4673 n = 1;
4674 while (*++pp)
4675 n++;
4676 G.global_argc = n;
4677
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004678 return EXIT_SUCCESS;
4679}
4680
4681static int builtin_shift(char **argv)
4682{
4683 int n = 1;
4684 if (argv[1]) {
4685 n = atoi(argv[1]);
4686 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004687 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004688 if (G.global_args_malloced) {
4689 int m = 1;
4690 while (m <= n)
4691 free(G.global_argv[m++]);
4692 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004693 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00004694 memmove(&G.global_argv[1], &G.global_argv[n+1],
4695 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004696 return EXIT_SUCCESS;
4697 }
4698 return EXIT_FAILURE;
4699}
4700
4701static int builtin_source(char **argv)
4702{
4703 FILE *input;
4704 int status;
4705
4706 if (argv[1] == NULL)
4707 return EXIT_FAILURE;
4708
4709 /* XXX search through $PATH is missing */
Denis Vlasenko5415c852008-07-21 23:05:26 +00004710 input = fopen_for_read(argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004711 if (!input) {
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004712 bb_error_msg("can't open '%s'", argv[1]);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004713 return EXIT_FAILURE;
4714 }
4715 close_on_exec_on(fileno(input));
4716
4717 /* Now run the file */
Denis Vlasenko87a86552008-07-29 19:43:10 +00004718 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004719 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00004720 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004721 status = parse_and_run_file(input);
4722 fclose(input);
4723 return status;
4724}
4725
4726static int builtin_umask(char **argv)
4727{
4728 mode_t new_umask;
4729 const char *arg = argv[1];
4730 char *end;
4731 if (arg) {
4732 new_umask = strtoul(arg, &end, 8);
4733 if (*end != '\0' || end == arg) {
4734 return EXIT_FAILURE;
4735 }
4736 } else {
4737 new_umask = umask(0);
4738 printf("%.3o\n", (unsigned) new_umask);
4739 }
4740 umask(new_umask);
4741 return EXIT_SUCCESS;
4742}
4743
4744static int builtin_unset(char **argv)
4745{
4746 /* bash always returns true */
4747 unset_local_var(argv[1]);
4748 return EXIT_SUCCESS;
4749}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004750
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004751#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004752static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004753{
Denis Vlasenko87a86552008-07-29 19:43:10 +00004754 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004755 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00004756 return EXIT_SUCCESS; /* bash compat */
4757 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004758 G.flag_break_continue++; /* BC_BREAK = 1 */
4759 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004760 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00004761 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4762 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004763 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00004764 G.flag_break_continue = BC_BREAK;
4765 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004766 }
4767 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00004768 if (G.depth_of_loop < G.depth_break_continue)
4769 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004770 return EXIT_SUCCESS;
4771}
4772
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00004773static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004774{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00004775 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4776 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00004777}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00004778#endif