blob: 032482c6d9f12d0bda1a70381ea838ed49f772de [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
7 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Denis Vlasenkoa8442002008-06-14 11:00:17 +000023 * o_addchr() derived from similar w_addchar function in glibc-2.2.
Eric Andersen25f27032001-04-26 23:22:31 +000024 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Denis Vlasenkoa8442002008-06-14 11:00:17 +000026 * miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000027 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
Eric Andersen25f27032001-04-26 23:22:31 +000041 * &> and >& redirection of stdout+stderr
42 * Brace Expansion
43 * Tilde Expansion
44 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000045 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000046 * Arithmetic Expansion
47 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000048 * reserved words: case, esac, 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 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000054 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000055 * port selected bugfixes from post-0.49 busybox lash - done?
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * change { and } from special chars to reserved words
57 * builtins: break, continue, eval, return, set, trap, ulimit
58 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000059 * check setting of global_argc and global_argv
Eric Andersen25f27032001-04-26 23:22:31 +000060 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000061 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000062 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
64 * memory leak finding and plugging - done?
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000065 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000066 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000067 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000068 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000069
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000070
Eric Andersen25f27032001-04-26 23:22:31 +000071#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000072/* #include <dmalloc.h> */
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000073
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000074#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000075
Denis Vlasenkod01ff132007-05-02 21:40:23 +000076
Denis Vlasenko05743d72008-02-10 12:10:08 +000077#if !BB_MMU && ENABLE_HUSH_TICK
78//#undef ENABLE_HUSH_TICK
79//#define ENABLE_HUSH_TICK 0
80#warning On NOMMU, hush command substitution is dangerous.
81#warning Dont use it for commands which produce lots of output.
82#warning For more info see shell/hush.c, generate_stream_from_list().
83#endif
84
85#if !BB_MMU && ENABLE_HUSH_JOB
86#undef ENABLE_HUSH_JOB
87#define ENABLE_HUSH_JOB 0
88#endif
89
90#if !ENABLE_HUSH_INTERACTIVE
91#undef ENABLE_FEATURE_EDITING
92#define ENABLE_FEATURE_EDITING 0
93#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
94#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +000095#endif
96
97
Denis Vlasenkod01ff132007-05-02 21:40:23 +000098/* If you comment out one of these below, it will be #defined later
99 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000100#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000101/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000102#define debug_printf_parse(...) do {} while (0)
103#define debug_print_tree(a, b) do {} while (0)
104#define debug_printf_exec(...) do {} while (0)
105#define debug_printf_jobs(...) do {} while (0)
106#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000107#define debug_printf_glob(...) do {} while (0)
108#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000109#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000110#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000111
112#ifndef debug_printf
113#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000114#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000115
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000116#ifndef debug_printf_parse
117#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000118#endif
119
120#ifndef debug_printf_exec
121#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
122#endif
123
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000124#ifndef debug_printf_jobs
125#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000126#define DEBUG_JOBS 1
127#else
128#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000129#endif
130
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000131#ifndef debug_printf_expand
132#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
133#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000134#else
135#define DEBUG_EXPAND 0
136#endif
137
138#ifndef debug_printf_glob
139#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
140#define DEBUG_GLOB 1
141#else
142#define DEBUG_GLOB 0
143#endif
144
145#ifndef debug_printf_list
146#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000147#endif
148
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000149#ifndef debug_printf_subst
150#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
151#endif
152
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000153#ifndef debug_printf_clean
154/* broken, of course, but OK for testing */
155static const char *indenter(int i)
156{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000157 static const char blanks[] ALIGN1 =
158 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000159 return &blanks[sizeof(blanks) - i - 1];
160}
161#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000162#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000163#endif
164
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000165#if DEBUG_EXPAND
166static void debug_print_strings(const char *prefix, char **vv)
167{
168 fprintf(stderr, "%s:\n", prefix);
169 while (*vv)
170 fprintf(stderr, " '%s'\n", *vv++);
171}
172#else
173#define debug_print_strings(prefix, vv) ((void)0)
174#endif
175
Denis Vlasenkof962a032007-11-23 12:50:54 +0000176/*
177 * Leak hunting. Use hush_leaktool.sh for post-processing.
178 */
179#ifdef FOR_HUSH_LEAKTOOL
Denis Vlasenkoccce59d2008-06-16 14:35:57 +0000180/* suppress "warning: no previous prototype..." */
181void *xxmalloc(int lineno, size_t size);
182void *xxrealloc(int lineno, void *ptr, size_t size);
183char *xxstrdup(int lineno, const char *str);
184void xxfree(void *ptr);
Denis Vlasenkof962a032007-11-23 12:50:54 +0000185void *xxmalloc(int lineno, size_t size)
186{
187 void *ptr = xmalloc((size + 0xff) & ~0xff);
188 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
189 return ptr;
190}
191void *xxrealloc(int lineno, void *ptr, size_t size)
192{
193 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
194 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
195 return ptr;
196}
197char *xxstrdup(int lineno, const char *str)
198{
199 char *ptr = xstrdup(str);
200 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
201 return ptr;
202}
203void xxfree(void *ptr)
204{
205 fprintf(stderr, "free %p\n", ptr);
206 free(ptr);
207}
208#define xmalloc(s) xxmalloc(__LINE__, s)
209#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
210#define xstrdup(s) xxstrdup(__LINE__, s)
211#define free(p) xxfree(p)
212#endif
213
214
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000215/* Keep unconditionally on for now */
216#define HUSH_DEBUG 1
217/* Do we support ANY keywords? */
218#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
219#define HAS_KEYWORDS 1
220#define IF_HAS_KEYWORDS(...) __VA_ARGS__
221#define IF_HAS_NO_KEYWORDS(...)
222#else
223#define HAS_KEYWORDS 0
224#define IF_HAS_KEYWORDS(...)
225#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
226#endif
227
228
Denis Vlasenko5703c222008-06-15 11:49:42 +0000229#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000230#define PARSEFLAG_EXIT_FROM_LOOP 1
Eric Andersen25f27032001-04-26 23:22:31 +0000231
232typedef enum {
233 REDIRECT_INPUT = 1,
234 REDIRECT_OVERWRITE = 2,
235 REDIRECT_APPEND = 3,
236 REDIRECT_HEREIS = 4,
237 REDIRECT_IO = 5
238} redir_type;
239
Denis Vlasenko55789c62008-06-18 16:30:42 +0000240/* The descrip member of this structure is only used to make
241 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000242static const struct {
243 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000244 signed char default_fd;
245 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000246} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000247 { 0, 0, "()" },
248 { O_RDONLY, 0, "<" },
249 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
250 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
251 { O_RDONLY, -1, "<<" },
252 { O_RDWR, 1, "<>" }
253};
254
255typedef enum {
256 PIPE_SEQ = 1,
257 PIPE_AND = 2,
258 PIPE_OR = 3,
259 PIPE_BG = 4,
260} pipe_style;
261
Eric Andersen25f27032001-04-26 23:22:31 +0000262typedef enum {
263 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000264#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000265 RES_IF = 1,
266 RES_THEN = 2,
267 RES_ELIF = 3,
268 RES_ELSE = 4,
269 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000270#endif
271#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000272 RES_FOR = 6,
273 RES_WHILE = 7,
274 RES_UNTIL = 8,
275 RES_DO = 9,
276 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000277 RES_IN = 11,
278#endif
279 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000280 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000281} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000282
Eric Andersen25f27032001-04-26 23:22:31 +0000283/* This holds pointers to the various results of parsing */
284struct p_context {
285 struct child_prog *child;
286 struct pipe *list_head;
287 struct pipe *pipe;
288 struct redir_struct *pending_redirect;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000289#if HAS_KEYWORDS
290 smallint ctx_res_w;
291 smallint ctx_inverted; /* "! cmd | cmd" */
292 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000293 struct p_context *stack;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000294#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000295};
296
297struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000298 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000299 char *rd_filename; /* filename */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000300 int fd; /* file descriptor being redirected */
301 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000302 smallint /*enum redir_type*/ rd_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000303};
304
305struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000306 pid_t pid; /* 0 if exited */
Denis Vlasenko55789c62008-06-18 16:30:42 +0000307 smallint is_stopped; /* is the program currently running? */
308 smallint subshell; /* flag, non-zero if group must be forked */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000309 char **argv; /* program name and arguments */
310 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000311 struct redir_struct *redirects; /* I/O redirections */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000312 struct pipe *family; /* pointer back to the child's parent pipe */
Eric Andersen25f27032001-04-26 23:22:31 +0000313};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000314/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
315 * and on execution these are substituted with their values.
316 * Substitution can make _several_ words out of one argv[n]!
317 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000318 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000319 */
Eric Andersen25f27032001-04-26 23:22:31 +0000320
321struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000322 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000323 int num_progs; /* total number of programs in job */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +0000324 int alive_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000325 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000326#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000327 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000328 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000329 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000330#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000331 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000332 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000333 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
334 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000335};
336
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000337/* On program start, environ points to initial environment.
338 * putenv adds new pointers into it, unsetenv removes them.
339 * Neither of these (de)allocates the strings.
340 * setenv allocates new strings in malloc space and does putenv,
341 * and thus setenv is unusable (leaky) for shell's purposes */
342#define setenv(...) setenv_is_leaky_dont_use()
343struct variable {
344 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000345 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000346 int max_len; /* if > 0, name is part of initial env; else name is malloced */
347 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000348 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000349};
350
Eric Andersen25f27032001-04-26 23:22:31 +0000351typedef struct {
352 char *data;
353 int length;
354 int maxlen;
Denis Vlasenko324a3fd2008-06-18 17:49:58 +0000355 /* Misnomer! it's not "quoting", it's "protection against globbing"!
356 * (by prepending \ to *, ?, [ and to \ too) */
Denis Vlasenkoff097622007-10-01 10:00:45 +0000357 smallint o_quote;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000358 smallint o_glob;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000359 smallint nonnull;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000360 smallint has_empty_slot;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000361 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
Eric Andersen25f27032001-04-26 23:22:31 +0000362} o_string;
Denis Vlasenko55789c62008-06-18 16:30:42 +0000363enum {
364 MAYBE_ASSIGNMENT = 0,
365 DEFINITELY_ASSIGNMENT = 1,
366 NOT_ASSIGNMENT = 2,
367};
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000368/* Used for initialization: o_string foo = NULL_O_STRING; */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000369#define NULL_O_STRING { NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000370
371/* I can almost use ordinary FILE *. Is open_memstream() universally
372 * available? Where is it documented? */
373struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000374 const char *p;
375 /* eof_flag=1: last char in ->p is really an EOF */
376 char eof_flag; /* meaningless if ->p == NULL */
377 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000378#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000379 smallint promptme;
380 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000381#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000382 FILE *file;
383 int (*get) (struct in_str *);
384 int (*peek) (struct in_str *);
385};
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000386#define i_getch(input) ((input)->get(input))
387#define i_peek(input) ((input)->peek(input))
Eric Andersen25f27032001-04-26 23:22:31 +0000388
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000389enum {
390 CHAR_ORDINARY = 0,
391 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
392 CHAR_IFS = 2, /* treated as ordinary if quoted */
393 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000394};
395
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000396#define HUSH_VER_STR "0.02"
397
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000398/* "Globals" within this file */
399
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000400/* Sorted roughly by size (smaller offsets == smaller code) */
401struct globals {
402#if ENABLE_HUSH_INTERACTIVE
403 /* 'interactive_fd' is a fd# open to ctty, if we have one
404 * _AND_ if we decided to act interactively */
405 int interactive_fd;
406 const char *PS1;
407 const char *PS2;
408#endif
409#if ENABLE_FEATURE_EDITING
410 line_input_t *line_input_state;
411#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000412 pid_t root_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000413#if ENABLE_HUSH_JOB
414 int run_list_level;
415 pid_t saved_task_pgrp;
416 pid_t saved_tty_pgrp;
417 int last_jobid;
418 struct pipe *job_list;
419 struct pipe *toplevel_list;
420 smallint ctrl_z_flag;
421#endif
422 smallint fake_mode;
423 /* these three support $?, $#, and $1 */
424 char **global_argv;
425 int global_argc;
426 int last_return_code;
427 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000428 const char *cwd;
429 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000430 struct variable *top_var; /* = &shell_ver (set in main()) */
431 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000432#if ENABLE_FEATURE_SH_STANDALONE
433 struct nofork_save_area nofork_save;
434#endif
435#if ENABLE_HUSH_JOB
436 sigjmp_buf toplevel_jb;
437#endif
438 unsigned char charmap[256];
439 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
440};
441
442#define G (*ptr_to_globals)
443
444#if !ENABLE_HUSH_INTERACTIVE
445enum { interactive_fd = 0 };
446#endif
447#if !ENABLE_HUSH_JOB
448enum { run_list_level = 0 };
449#endif
450
451#if ENABLE_HUSH_INTERACTIVE
452#define interactive_fd (G.interactive_fd )
453#define PS1 (G.PS1 )
454#define PS2 (G.PS2 )
455#endif
456#if ENABLE_FEATURE_EDITING
457#define line_input_state (G.line_input_state)
458#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000459#define root_pid (G.root_pid )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000460#if ENABLE_HUSH_JOB
461#define run_list_level (G.run_list_level )
462#define saved_task_pgrp (G.saved_task_pgrp )
463#define saved_tty_pgrp (G.saved_tty_pgrp )
464#define last_jobid (G.last_jobid )
465#define job_list (G.job_list )
466#define toplevel_list (G.toplevel_list )
467#define toplevel_jb (G.toplevel_jb )
468#define ctrl_z_flag (G.ctrl_z_flag )
469#endif /* JOB */
470#define global_argv (G.global_argv )
471#define global_argc (G.global_argc )
472#define last_return_code (G.last_return_code)
473#define ifs (G.ifs )
474#define fake_mode (G.fake_mode )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000475#define cwd (G.cwd )
476#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000477#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000478#define shell_ver (G.shell_ver )
479#if ENABLE_FEATURE_SH_STANDALONE
480#define nofork_save (G.nofork_save )
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000481#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000482#if ENABLE_HUSH_JOB
483#define toplevel_jb (G.toplevel_jb )
484#endif
485#define charmap (G.charmap )
486#define user_input_buf (G.user_input_buf )
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000487#define INIT_G() do { \
488 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
489} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000490
491
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000492#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
493
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000494#if 1
495/* Normal */
496static void syntax(const char *msg)
497{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000498 /* Was using fancy stuff:
499 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
500 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
501 void (*fp)(const char *s, ...);
502
503 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
504 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000505}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000506
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000507#else
508/* Debug */
509static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000510{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000511 void (*fp)(const char *s, ...);
512
513 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
514 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000515}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000516#define syntax(str) syntax_lineno(__LINE__)
517#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000518
519/* Index of subroutines: */
Eric Andersen25f27032001-04-26 23:22:31 +0000520/* in_str manipulations: */
521static int static_get(struct in_str *i);
522static int static_peek(struct in_str *i);
523static int file_get(struct in_str *i);
524static int file_peek(struct in_str *i);
525static void setup_file_in_str(struct in_str *i, FILE *f);
526static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000527/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000528#if !defined(DEBUG_CLEAN)
529#define free_pipe_list(head, indent) free_pipe_list(head)
530#define free_pipe(pi, indent) free_pipe(pi)
531#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000532static int free_pipe_list(struct pipe *head, int indent);
533static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000534/* really run the final data structures: */
535static int setup_redirects(struct child_prog *prog, int squirrel[]);
Denis Vlasenko05743d72008-02-10 12:10:08 +0000536static int run_list(struct pipe *pi);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000537#if BB_MMU
538#define pseudo_exec_argv(ptrs2free, argv) pseudo_exec_argv(argv)
539#define pseudo_exec(ptrs2free, child) pseudo_exec(child)
540#endif
541static void pseudo_exec_argv(char **ptrs2free, char **argv) ATTRIBUTE_NORETURN;
542static void pseudo_exec(char **ptrs2free, struct child_prog *child) ATTRIBUTE_NORETURN;
Denis Vlasenko05743d72008-02-10 12:10:08 +0000543static int run_pipe(struct pipe *pi);
Eric Andersen25f27032001-04-26 23:22:31 +0000544/* data structure manipulation: */
545static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
546static void initialize_context(struct p_context *ctx);
547static int done_word(o_string *dest, struct p_context *ctx);
548static int done_command(struct p_context *ctx);
Denis Vlasenkoa8442002008-06-14 11:00:17 +0000549static void done_pipe(struct p_context *ctx, pipe_style type);
Eric Andersen25f27032001-04-26 23:22:31 +0000550/* primary string parsing: */
551static int redirect_dup_num(struct in_str *input);
552static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000553#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000554static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000555 struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000556#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000557static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000558static const char *lookup_param(const char *src);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000559static int handle_dollar(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +0000560 struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000561static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
Eric Andersen25f27032001-04-26 23:22:31 +0000562/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000563static int parse_and_run_stream(struct in_str *inp, int parse_flag);
564static int parse_and_run_string(const char *s, int parse_flag);
565static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000566/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000567static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000568#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000569static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000570static void insert_bg_job(struct pipe *pi);
571static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000572static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000573#else
574int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
575#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000576/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000577static char **expand_strvec_to_strvec(char **argv);
578/* used for eval */
579static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000580/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000581static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000582static struct variable *get_local_var(const char *name);
583static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000584static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000585
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000586
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000587static int glob_needed(const char *s)
588{
589 while (*s) {
590 if (*s == '\\')
591 s++;
592 if (*s == '*' || *s == '[' || *s == '?')
593 return 1;
594 s++;
595 }
596 return 0;
597}
598
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000599static int is_assignment(const char *s)
600{
601 if (!s || !isalpha(*s))
602 return 0;
603 s++;
604 while (isalnum(*s) || *s == '_')
605 s++;
606 return *s == '=';
607}
608
Denis Vlasenko55789c62008-06-18 16:30:42 +0000609/* Replace each \x with x in place, return ptr past NUL. */
610static char *unbackslash(char *src)
611{
612 char *dst = src;
613 while (1) {
614 if (*src == '\\')
615 src++;
616 if ((*dst++ = *src++) == '\0')
617 break;
618 }
619 return dst;
620}
621
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000622static char **add_malloced_strings_to_strings(char **strings, char **add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000623{
624 int i;
625 unsigned count1;
626 unsigned count2;
627 char **v;
628
629 v = strings;
630 count1 = 0;
631 if (v) {
632 while (*v) {
633 count1++;
634 v++;
635 }
636 }
637 count2 = 0;
638 v = add;
639 while (*v) {
640 count2++;
641 v++;
642 }
643 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
644 v[count1 + count2] = NULL;
645 i = count2;
646 while (--i >= 0)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000647 v[count1 + i] = add[i];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000648 return v;
649}
650
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000651static char **add_malloced_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000652{
653 char *v[2];
654
655 v[0] = add;
656 v[1] = NULL;
657
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000658 return add_malloced_strings_to_strings(strings, v);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000659}
660
661static void free_strings(char **strings)
662{
663 if (strings) {
664 char **v = strings;
665 while (*v)
666 free(*v++);
667 free(strings);
668 }
669}
670
Denis Vlasenko76d50412008-06-10 16:19:39 +0000671#if !BB_MMU
672#define EXTRA_PTRS 5 /* 1 for NULL, 1 for args, 3 for paranoid reasons */
673static char **alloc_ptrs(char **argv)
674{
675 char **v = argv;
676 while (*v)
677 v++;
678 return xzalloc((v - argv + EXTRA_PTRS) * sizeof(v[0]));
679}
680#endif
681
682
Denis Vlasenko83506862007-11-23 13:11:42 +0000683/* Function prototypes for builtins */
684static int builtin_cd(char **argv);
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000685static int builtin_echo(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000686static int builtin_eval(char **argv);
687static int builtin_exec(char **argv);
688static int builtin_exit(char **argv);
689static int builtin_export(char **argv);
690#if ENABLE_HUSH_JOB
691static int builtin_fg_bg(char **argv);
692static int builtin_jobs(char **argv);
693#endif
694#if ENABLE_HUSH_HELP
695static int builtin_help(char **argv);
696#endif
697static int builtin_pwd(char **argv);
698static int builtin_read(char **argv);
699static int builtin_test(char **argv);
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000700static int builtin_true(char **argv);
Denis Vlasenko83506862007-11-23 13:11:42 +0000701static int builtin_set(char **argv);
702static int builtin_shift(char **argv);
703static int builtin_source(char **argv);
704static int builtin_umask(char **argv);
705static int builtin_unset(char **argv);
706//static int builtin_not_written(char **argv);
707
Eric Andersen25f27032001-04-26 23:22:31 +0000708/* Table of built-in functions. They can be forked or not, depending on
709 * context: within pipes, they fork. As simple commands, they do not.
710 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000711 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000712 * For example, 'unset foo | whatever' will parse and run, but foo will
713 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000714struct built_in_command {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000715 const char *cmd;
716 int (*function)(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000717#if ENABLE_HUSH_HELP
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000718 const char *descr;
Denis Vlasenko06810332007-05-21 23:30:54 +0000719#define BLTIN(cmd, func, help) { cmd, func, help }
720#else
721#define BLTIN(cmd, func, help) { cmd, func }
722#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000723};
724
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000725/* For now, echo and test are unconditionally enabled.
726 * Maybe make it configurable? */
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000727static const struct built_in_command bltins[] = {
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000728 BLTIN("." , builtin_source, "Run commands in a file"),
729 BLTIN(":" , builtin_true, "No-op"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000730 BLTIN("[" , builtin_test, "Test condition"),
731 BLTIN("[[" , builtin_test, "Test condition"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000732#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000733 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000734#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000735// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000736 BLTIN("cd" , builtin_cd, "Change directory"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000737// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
Denis Vlasenko5bc593c2007-11-23 21:20:21 +0000738 BLTIN("echo" , builtin_echo, "Write strings to stdout"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000739 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000740 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
741 BLTIN("exit" , builtin_exit, "Exit"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000742 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000743#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000744 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000745 BLTIN("jobs" , builtin_jobs, "List active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000746#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000747 BLTIN("pwd" , builtin_pwd, "Print current directory"),
748 BLTIN("read" , builtin_read, "Input environment variable"),
749// BLTIN("return", builtin_not_written, "Return from a function"),
750 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
751 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
752// BLTIN("trap" , builtin_not_written, "Trap signals"),
Denis Vlasenko83506862007-11-23 13:11:42 +0000753 BLTIN("test" , builtin_test, "Test condition"),
Denis Vlasenkodd316dd2008-06-14 15:50:55 +0000754// BLTIN("ulimit", builtin_not_written, "Control resource limits"),
755 BLTIN("umask" , builtin_umask, "Set file creation mask"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000756 BLTIN("unset" , builtin_unset, "Unset environment variable"),
Denis Vlasenko06810332007-05-21 23:30:54 +0000757#if ENABLE_HUSH_HELP
758 BLTIN("help" , builtin_help, "List shell built-in commands"),
759#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000760};
761
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000762
Denis Vlasenko4830fc52008-05-25 21:50:55 +0000763/* Signals are grouped, we handle them in batches */
764static void set_misc_sighandler(void (*handler)(int))
765{
766 bb_signals(0
767 + (1 << SIGINT)
768 + (1 << SIGQUIT)
769 + (1 << SIGTERM)
770 , handler);
771}
772
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000773#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000774
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000775static void set_fatal_sighandler(void (*handler)(int))
776{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000777 bb_signals(0
778 + (1 << SIGILL)
779 + (1 << SIGTRAP)
780 + (1 << SIGABRT)
781 + (1 << SIGFPE)
782 + (1 << SIGBUS)
783 + (1 << SIGSEGV)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000784 /* bash 3.2 seems to handle these just like 'fatal' ones */
Denis Vlasenko25591c32008-02-16 22:58:56 +0000785 + (1 << SIGHUP)
786 + (1 << SIGPIPE)
787 + (1 << SIGALRM)
788 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000789}
790static void set_jobctrl_sighandler(void (*handler)(int))
791{
Denis Vlasenko25591c32008-02-16 22:58:56 +0000792 bb_signals(0
793 + (1 << SIGTSTP)
794 + (1 << SIGTTIN)
795 + (1 << SIGTTOU)
796 , handler);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000797}
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000798/* SIGCHLD is special and handled separately */
799
800static void set_every_sighandler(void (*handler)(int))
801{
802 set_fatal_sighandler(handler);
803 set_jobctrl_sighandler(handler);
804 set_misc_sighandler(handler);
805 signal(SIGCHLD, handler);
806}
807
Denis Vlasenko68404f12008-03-17 09:00:54 +0000808static void handler_ctrl_c(int sig ATTRIBUTE_UNUSED)
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000809{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000810 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000811// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000812 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000813}
814
Denis Vlasenko68404f12008-03-17 09:00:54 +0000815static void handler_ctrl_z(int sig ATTRIBUTE_UNUSED)
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000816{
817 pid_t pid;
818
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000819 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000820 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000821 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000822 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000823 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000824 if (!pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +0000825 if (ENABLE_HUSH_JOB)
826 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000827 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000828 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000829 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000830 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000831 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000832 /* return to nofork, it will eventually exit now,
833 * not return back to shell */
834 return;
835 }
836 /* parent */
837 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000838 toplevel_list->pgrp = pid; /* child is in its own pgrp */
839 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000840 /* parent needs to longjmp out of running nofork.
841 * we will "return" exitcode 0, with child put in background */
842// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000843 debug_printf_jobs("siglongjmp in parent\n");
844 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000845}
846
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000847/* Restores tty foreground process group, and exits.
848 * May be called as signal handler for fatal signal
849 * (will faithfully resend signal to itself, producing correct exit state)
850 * or called directly with -EXITCODE.
851 * We also call it if xfunc is exiting. */
852static void sigexit(int sig) ATTRIBUTE_NORETURN;
853static void sigexit(int sig)
854{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000855 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000856 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000857
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000858 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000859 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000860
861 /* Not a signal, just exit */
862 if (sig <= 0)
863 _exit(- sig);
864
Denis Vlasenko400d8bb2008-02-24 13:36:01 +0000865 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000866}
867
868/* Restores tty foreground process group, and exits. */
869static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
870static void hush_exit(int exitcode)
871{
872 fflush(NULL); /* flush all streams */
873 sigexit(- (exitcode & 0xff));
874}
875
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000876#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000877
878#define set_fatal_sighandler(handler) ((void)0)
879#define set_jobctrl_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000880#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000881
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000882#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000883
884
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000885static const char *set_cwd(void)
886{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000887 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000888 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000889 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000890 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000891 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000892 return cwd;
893}
894
Denis Vlasenko83506862007-11-23 13:11:42 +0000895
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000896/*
897 * o_string support
898 */
899#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +0000900
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000901static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000902{
903 o->length = 0;
904 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000905 if (o->data)
906 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000907}
908
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000909static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +0000910{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +0000911 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000912 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +0000913}
914
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000915static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000916{
917 if (o->length + len > o->maxlen) {
918 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
919 o->data = xrealloc(o->data, 1 + o->maxlen);
920 }
921}
922
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000923static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000924{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000925 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
926 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000927 o->data[o->length] = ch;
928 o->length++;
929 o->data[o->length] = '\0';
930}
931
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000932static void o_addstr(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000933{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +0000934 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +0000935 memcpy(&o->data[o->length], str, len);
936 o->length += len;
937 o->data[o->length] = '\0';
938}
939
Denis Vlasenko55789c62008-06-18 16:30:42 +0000940static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
941{
942 while (len) {
943 o_addchr(o, *str);
944 if (*str++ == '\\'
945 && (*str != '*' && *str != '?' && *str != '[')
946 ) {
947 o_addchr(o, '\\');
948 }
949 len--;
950 }
951}
952
Eric Andersen25f27032001-04-26 23:22:31 +0000953/* My analysis of quoting semantics tells me that state information
954 * is associated with a destination, not a source.
955 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000956static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +0000957{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000958 int sz = 1;
959 if (strchr("*?[\\", ch)) {
960 sz++;
961 o->data[o->length] = '\\';
962 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +0000963 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000964 o_grow_by(o, sz);
965 o->data[o->length] = ch;
966 o->length++;
967 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +0000968}
969
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000970static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000971{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000972 int sz = 1;
973 if (o->o_quote && strchr("*?[\\", ch)) {
974 sz++;
975 o->data[o->length] = '\\';
976 o->length++;
977 }
978 o_grow_by(o, sz);
979 o->data[o->length] = ch;
980 o->length++;
981 o->data[o->length] = '\0';
982}
983
984static void o_addQstr(o_string *o, const char *str, int len)
985{
986 if (!o->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +0000987 o_addstr(o, str, len);
988 return;
989 }
990 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +0000991 char ch;
992 int sz;
993 int ordinary_cnt = strcspn(str, "*?[\\");
994 if (ordinary_cnt > len) /* paranoia */
995 ordinary_cnt = len;
996 o_addstr(o, str, ordinary_cnt);
997 if (ordinary_cnt == len)
998 return;
999 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001000 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001001
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001002 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001003 sz = 1;
1004 if (ch) { /* it is necessarily one of "*?[\\" */
1005 sz++;
1006 o->data[o->length] = '\\';
1007 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001008 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001009 o_grow_by(o, sz);
1010 o->data[o->length] = ch;
1011 o->length++;
1012 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001013 }
1014}
1015
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001016/* A special kind of o_string for $VAR and `cmd` expansion.
1017 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001018 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001019 * list[i] contains an INDEX (int!) into this string data.
1020 * It means that if list[] needs to grow, data needs to be moved higher up
1021 * but list[i]'s need not be modified.
1022 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001023 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001024 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1025 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001026#if DEBUG_EXPAND || DEBUG_GLOB
1027static void debug_print_list(const char *prefix, o_string *o, int n)
1028{
1029 char **list = (char**)o->data;
1030 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1031 int i = 0;
1032 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1033 prefix, list, n, string_start, o->length, o->maxlen);
1034 while (i < n) {
1035 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1036 o->data + (int)list[i] + string_start,
1037 o->data + (int)list[i] + string_start);
1038 i++;
1039 }
1040 if (n) {
1041 const char *p = o->data + (int)list[n - 1] + string_start;
1042 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1043 }
1044}
1045#else
1046#define debug_print_list(prefix, o, n) ((void)0)
1047#endif
1048
1049/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1050 * in list[n] so that it points past last stored byte so far.
1051 * It returns n+1. */
1052static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001053{
1054 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001055 int string_start;
1056 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001057
1058 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001059 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1060 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001061 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001062 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001063 /* list[n] points to string_start, make space for 16 more pointers */
1064 o->maxlen += 0x10 * sizeof(list[0]);
1065 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001066 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001067 memmove(list + n + 0x10, list + n, string_len);
1068 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001069 } else
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001070 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001071 } else {
1072 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001073 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1074 string_len = o->length - string_start;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001075 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001076 o->has_empty_slot = 0;
1077 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001078 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001079 return n + 1;
1080}
1081
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001082/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001083static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001084{
1085 char **list = (char**)o->data;
1086 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1087
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001088 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001089}
1090
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001091/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001092 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001093static int o_glob(o_string *o, int n)
1094{
1095 glob_t globdata;
1096 int gr;
1097 char *pattern;
1098
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001099 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001100 if (!o->data)
1101 return o_save_ptr_helper(o, n);
1102 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001103 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001104 if (!glob_needed(pattern)) {
1105 literal:
1106 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001107 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001108 return o_save_ptr_helper(o, n);
1109 }
1110
1111 memset(&globdata, 0, sizeof(globdata));
1112 gr = glob(pattern, 0, NULL, &globdata);
1113 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1114 if (gr == GLOB_NOSPACE)
1115 bb_error_msg_and_die("out of memory during glob");
1116 if (gr == GLOB_NOMATCH) {
1117 globfree(&globdata);
1118 goto literal;
1119 }
1120 if (gr != 0) { /* GLOB_ABORTED ? */
1121//TODO: testcase for bad glob pattern behavior
1122 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1123 }
1124 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1125 char **argv = globdata.gl_pathv;
1126 o->length = pattern - o->data; /* "forget" pattern */
1127 while (1) {
1128 o_addstr(o, *argv, strlen(*argv) + 1);
1129 n = o_save_ptr_helper(o, n);
1130 argv++;
1131 if (!*argv)
1132 break;
1133 }
1134 }
1135 globfree(&globdata);
1136 if (DEBUG_GLOB)
1137 debug_print_list("o_glob returning", o, n);
1138 return n;
1139}
1140
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001141/* If o->o_glob == 1, glob the string so far remembered.
1142 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001143static int o_save_ptr(o_string *o, int n)
1144{
1145 if (o->o_glob)
1146 return o_glob(o, n); /* o_save_ptr_helper is inside */
1147 return o_save_ptr_helper(o, n);
1148}
1149
1150/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001151static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001152{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001153 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001154 int string_start;
1155
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001156 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1157 if (DEBUG_EXPAND)
1158 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001159 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001160 list = (char**)o->data;
1161 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1162 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001163 while (n) {
1164 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001165 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001166 }
1167 return list;
1168}
1169
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001170
1171/*
1172 * in_str support
1173 */
Eric Andersen25f27032001-04-26 23:22:31 +00001174static int static_get(struct in_str *i)
1175{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001176 int ch = *i->p++;
1177 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001178 return ch;
1179}
1180
1181static int static_peek(struct in_str *i)
1182{
1183 return *i->p;
1184}
1185
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001186#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001187
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001188#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001189static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001190{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001191#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001192 PS1 = NULL;
1193#else
1194 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001195 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001196 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001197#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001198}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001199#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001200
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001201static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001202{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001203 const char *prompt_str;
1204 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001205#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001206 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001207 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001208 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001209 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1210 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001211 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001212 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001213 }
1214#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001215 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001216#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001217 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001218 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001219}
1220
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001221static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001222{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001223 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001224 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001225
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001226 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001227#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001228 /* Enable command line editing only while a command line
Denis Vlasenkoe376d452008-02-20 22:23:24 +00001229 * is actually being read */
1230 do {
1231 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1232 } while (r == 0); /* repeat if Ctrl-C */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001233 i->eof_flag = (r < 0);
1234 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001235 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1236 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001237 }
Eric Andersen25f27032001-04-26 23:22:31 +00001238#else
1239 fputs(prompt_str, stdout);
1240 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001241 user_input_buf[0] = r = fgetc(i->file);
1242 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001243 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001244#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001245 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001246}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001247
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001248#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001249
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001250/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001251 * and gets data back from the user */
1252static int file_get(struct in_str *i)
1253{
1254 int ch;
1255
Eric Andersen25f27032001-04-26 23:22:31 +00001256 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001257 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001258#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001259 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001260#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001261 ch = *i->p++;
1262 if (i->eof_flag && !*i->p)
1263 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001264 } else {
1265 /* need to double check i->file because we might be doing something
1266 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001267#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001268 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001269 do {
1270 get_user_input(i);
1271 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001272 i->promptmode = 1; /* PS2 */
1273 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001274 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001275 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001276#endif
1277 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001278 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001279 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001280#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001281 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001282 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001283#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001284 return ch;
1285}
1286
1287/* All the callers guarantee this routine will never be
1288 * used right after a newline, so prompting is not needed.
1289 */
1290static int file_peek(struct in_str *i)
1291{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001292 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001293 if (i->p && *i->p) {
1294 if (i->eof_flag && !i->p[1])
1295 return EOF;
1296 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001297 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001298 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001299 i->eof_flag = (ch == EOF);
1300 i->peek_buf[0] = ch;
1301 i->peek_buf[1] = '\0';
1302 i->p = i->peek_buf;
1303 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001304 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001305}
1306
1307static void setup_file_in_str(struct in_str *i, FILE *f)
1308{
1309 i->peek = file_peek;
1310 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001311#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001312 i->promptme = 1;
1313 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001314#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001315 i->file = f;
1316 i->p = NULL;
1317}
1318
1319static void setup_string_in_str(struct in_str *i, const char *s)
1320{
1321 i->peek = static_peek;
1322 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001323#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001324 i->promptme = 1;
1325 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001326#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001327 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001328 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001329}
1330
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001331
Eric Andersen25f27032001-04-26 23:22:31 +00001332/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1333 * and stderr if they are redirected. */
1334static int setup_redirects(struct child_prog *prog, int squirrel[])
1335{
1336 int openfd, mode;
1337 struct redir_struct *redir;
1338
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001339 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001340 if (redir->dup == -1 && redir->rd_filename == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001341 /* something went wrong in the parse. Pretend it didn't happen */
1342 continue;
1343 }
Eric Andersen25f27032001-04-26 23:22:31 +00001344 if (redir->dup == -1) {
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001345 char *p;
Denis Vlasenko55789c62008-06-18 16:30:42 +00001346 mode = redir_table[redir->rd_type].mode;
1347//TODO: check redir to names like '\\'
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00001348 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00001349 openfd = open_or_warn(p, mode);
1350 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00001351 if (openfd < 0) {
1352 /* this could get lost if stderr has been redirected, but
1353 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001354 return 1;
1355 }
1356 } else {
1357 openfd = redir->dup;
1358 }
1359
1360 if (openfd != redir->fd) {
1361 if (squirrel && redir->fd < 3) {
1362 squirrel[redir->fd] = dup(redir->fd);
1363 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001364 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001365 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001366 } else {
1367 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001368 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001369 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001370 }
Eric Andersen25f27032001-04-26 23:22:31 +00001371 }
1372 }
1373 return 0;
1374}
1375
1376static void restore_redirects(int squirrel[])
1377{
1378 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001379 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001380 fd = squirrel[i];
1381 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001382 /* We simply die on error */
1383 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001384 }
1385 }
1386}
1387
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001388
Denis Vlasenko05743d72008-02-10 12:10:08 +00001389/* Called after [v]fork() in run_pipe(), or from builtin_exec().
Denis Vlasenko8412d792007-10-01 09:59:47 +00001390 * Never returns.
1391 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001392 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001393 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko76d50412008-06-10 16:19:39 +00001394static void pseudo_exec_argv(char **ptrs2free, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001395{
Eric Andersen78a7c992001-05-15 16:30:25 +00001396 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001397 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001398 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001399
Denis Vlasenko1359da62007-04-21 23:27:30 +00001400 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001401 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001402 getpid(), argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001403 p = expand_string_to_string(argv[i]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001404#if !BB_MMU
1405 *ptrs2free++ = p;
1406#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00001407 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001408 }
1409 argv += i;
1410 /* If a variable is assigned in a forest, and nobody listens,
1411 * was it ever really set?
1412 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001413 if (!argv[0])
Denis Vlasenko1359da62007-04-21 23:27:30 +00001414 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001415
Denis Vlasenko170435c2007-05-23 13:01:10 +00001416 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001417#if !BB_MMU
1418 *ptrs2free++ = (char*) argv;
1419#endif
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001420
Denis Vlasenko1359da62007-04-21 23:27:30 +00001421 /*
1422 * Check if the command matches any of the builtins.
1423 * Depending on context, this might be redundant. But it's
1424 * easier to waste a few CPU cycles than it is to figure out
1425 * if this is one of those cases.
1426 */
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001427 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001428 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001429 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001430 rcode = x->function(argv);
1431 fflush(stdout);
1432 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001433 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001434 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001435
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001436 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001437#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001438 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001439 int a = find_applet_by_name(argv[0]);
1440 if (a >= 0) {
1441 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001442 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001443// is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1444 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001445 }
1446 /* re-exec ourselves with the new arguments */
1447 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001448 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001449 /* If they called chroot or otherwise made the binary no longer
1450 * executable, fall through */
1451 }
1452 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001453#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001454
1455 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001456 execvp(argv[0], argv);
1457 bb_perror_msg("cannot exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00001458 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001459}
1460
Denis Vlasenko05743d72008-02-10 12:10:08 +00001461/* Called after [v]fork() in run_pipe()
Denis Vlasenko8412d792007-10-01 09:59:47 +00001462 */
Denis Vlasenko76d50412008-06-10 16:19:39 +00001463static void pseudo_exec(char **ptrs2free, struct child_prog *child)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001464{
Denis Vlasenko05743d72008-02-10 12:10:08 +00001465 if (child->argv)
Denis Vlasenko76d50412008-06-10 16:19:39 +00001466 pseudo_exec_argv(ptrs2free, child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001467
1468 if (child->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001469#if !BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00001470 bb_error_msg_and_die("nested lists are not supported on NOMMU");
Denis Vlasenko8412d792007-10-01 09:59:47 +00001471#else
Denis Vlasenko3b492162007-12-24 14:26:57 +00001472 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00001473 debug_printf_exec("pseudo_exec: run_list\n");
1474 rcode = run_list(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001475 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001476 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001477 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001478#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001479 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001480
1481 /* Can happen. See what bash does with ">foo" by itself. */
1482 debug_printf("trying to pseudo_exec null command\n");
1483 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001484}
1485
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001486#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001487static const char *get_cmdtext(struct pipe *pi)
1488{
1489 char **argv;
1490 char *p;
1491 int len;
1492
1493 /* This is subtle. ->cmdtext is created only on first backgrounding.
1494 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001495 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001496 if (pi->cmdtext)
1497 return pi->cmdtext;
1498 argv = pi->progs[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00001499 if (!argv || !argv[0]) {
1500 pi->cmdtext = xzalloc(1);
1501 return pi->cmdtext;
1502 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001503
1504 len = 0;
1505 do len += strlen(*argv) + 1; while (*++argv);
1506 pi->cmdtext = p = xmalloc(len);
1507 argv = pi->progs[0].argv;
1508 do {
1509 len = strlen(*argv);
1510 memcpy(p, *argv, len);
1511 p += len;
1512 *p++ = ' ';
1513 } while (*++argv);
1514 p[-1] = '\0';
1515 return pi->cmdtext;
1516}
1517
Eric Andersenbafd94f2001-05-02 16:11:59 +00001518static void insert_bg_job(struct pipe *pi)
1519{
1520 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001521 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001522
1523 /* Linear search for the ID of the job to use */
1524 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001525 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001526 if (thejob->jobid >= pi->jobid)
1527 pi->jobid = thejob->jobid + 1;
1528
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001529 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001530 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001531 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001532 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001533 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001534 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001535 thejob->next = xmalloc(sizeof(*thejob));
1536 thejob = thejob->next;
1537 }
1538
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001539 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001540 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001541 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1542 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1543 for (i = 0; i < pi->num_progs; i++) {
1544// TODO: do we really need to have so many fields which are just dead weight
1545// at execution stage?
1546 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001547 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001548 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001549 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001550 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001551
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001552 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001553 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001554 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001555 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001556 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001557}
1558
Eric Andersenbafd94f2001-05-02 16:11:59 +00001559static void remove_bg_job(struct pipe *pi)
1560{
1561 struct pipe *prev_pipe;
1562
Eric Andersenc798b072001-06-22 06:23:03 +00001563 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001564 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001565 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001566 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001567 while (prev_pipe->next != pi)
1568 prev_pipe = prev_pipe->next;
1569 prev_pipe->next = pi->next;
1570 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001571 if (job_list)
1572 last_jobid = job_list->jobid;
1573 else
1574 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001575}
Eric Andersen028b65b2001-06-28 01:10:11 +00001576
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001577/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001578static void delete_finished_bg_job(struct pipe *pi)
1579{
1580 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001581 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001582 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001583 free(pi);
1584}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001585#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001586
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001587/* Check to see if any processes have exited -- if they
1588 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001589static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001590{
Eric Andersenc798b072001-06-22 06:23:03 +00001591 int attributes;
1592 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001593#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001594 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001595#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001596 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001597 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001598
Eric Andersenc798b072001-06-22 06:23:03 +00001599 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001600 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00001601 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00001602
Denis Vlasenko1359da62007-04-21 23:27:30 +00001603/* Do we do this right?
1604 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001605 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001606 * [3]+ Stopped sleep 20 | false
1607 * bash-3.00# echo $?
1608 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1609 */
1610
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001611//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1612//are stopped. Testcase: "cat | cat" in a script (not on command line)
1613// + killall -STOP cat
1614
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001615 wait_more:
Denis Vlasenkofb0eba72008-01-02 19:55:04 +00001616// TODO: safe_waitpid?
Eric Andersenc798b072001-06-22 06:23:03 +00001617 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001618 int i;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001619 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001620#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00001621 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001622 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001623 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1624 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001625 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001626 childpid, WTERMSIG(status), WEXITSTATUS(status));
1627 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001628 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001629 childpid, WEXITSTATUS(status));
1630#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001631 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001632 if (fg_pipe) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001633 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001634 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001635 if (fg_pipe->progs[i].pid != childpid)
1636 continue;
1637 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1638 if (dead) {
1639 fg_pipe->progs[i].pid = 0;
1640 fg_pipe->alive_progs--;
1641 if (i == fg_pipe->num_progs - 1) {
1642 /* last process gives overall exitstatus */
1643 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001644 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00001645 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001646 } else {
1647 fg_pipe->progs[i].is_stopped = 1;
1648 fg_pipe->stopped_progs++;
Eric Andersenc798b072001-06-22 06:23:03 +00001649 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001650 debug_printf_jobs("fg_pipe: alive_progs %d stopped_progs %d\n",
1651 fg_pipe->alive_progs, fg_pipe->stopped_progs);
1652 if (fg_pipe->alive_progs - fg_pipe->stopped_progs <= 0) {
1653 /* All processes in fg pipe have exited/stopped */
1654#if ENABLE_HUSH_JOB
1655 if (fg_pipe->alive_progs)
1656 insert_bg_job(fg_pipe);
1657#endif
1658 return rcode;
1659 }
1660 /* There are still running processes in the fg pipe */
1661 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00001662 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001663 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001664 }
1665
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001666#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001667 /* We asked to wait for bg or orphaned children */
1668 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001669 for (pi = job_list; pi; pi = pi->next) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001670 for (i = 0; i < pi->num_progs; i++) {
1671 if (pi->progs[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001672 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001673 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001674 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001675 /* Happens when shell is used as init process (init=/bin/sh) */
1676 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001677 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00001678
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001679 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001680 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001681 /* child exited */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001682 pi->progs[i].pid = 0;
1683 pi->alive_progs--;
1684 if (!pi->alive_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001685 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001686 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001687 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001688 }
1689 } else {
1690 /* child stopped */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001691 pi->progs[i].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001692 pi->stopped_progs++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001693 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001694#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001695 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001696
Denis Vlasenko1359da62007-04-21 23:27:30 +00001697 /* wait found no children or failed */
1698
1699 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001700 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001701 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001702}
1703
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001704#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001705static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1706{
1707 pid_t p;
1708 int rcode = checkjobs(fg_pipe);
1709 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001710 p = getpgid(0); /* pgid of our process */
1711 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001712 tcsetpgrp(interactive_fd, p);
1713// if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1714// bb_perror_msg("tcsetpgrp-4a");
Denis Vlasenko52881e92007-04-21 13:42:52 +00001715 return rcode;
1716}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001717#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001718
Denis Vlasenko05743d72008-02-10 12:10:08 +00001719/* run_pipe() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001720 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001721 *
1722 * return code is normally -1, when the caller has to wait for children
1723 * to finish to determine the exit status of the pipe. If the pipe
1724 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00001725 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00001726 * return value.
1727 *
1728 * The input of the pipe is always stdin, the output is always
1729 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1730 * because it tries to avoid running the command substitution in
1731 * subshell, when that is in fact necessary. The subshell process
1732 * now has its stdout directed to the input of the appropriate pipe,
1733 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001734 *
1735 * Returns -1 only if started some children. IOW: we have to
1736 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001737 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001738static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001739{
1740 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001741 int nextin;
1742 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001743 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001744 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001745 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001746 /* it is not always needed, but we aim to smaller code */
1747 int squirrel[] = { -1, -1, -1 };
1748 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001749 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001750
Denis Vlasenko05743d72008-02-10 12:10:08 +00001751 debug_printf_exec("run_pipe start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001752
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001753#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001754 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001755#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001756 pi->alive_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001757 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001758
1759 /* Check if this is a simple builtin (not part of a pipe).
1760 * Builtins within pipes have to fork anyway, and are handled in
1761 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1762 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001763 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001764 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001765 debug_printf("non-subshell grouping\n");
1766 setup_redirects(child, squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001767 debug_printf_exec(": run_list\n");
1768 rcode = run_list(child->group) & 0xff;
Eric Andersen04407e52001-06-07 16:42:05 +00001769 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001770 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001771 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00001772 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001773 }
1774
Denis Vlasenko1359da62007-04-21 23:27:30 +00001775 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001776 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001777 char **argv = child->argv;
1778
1779 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001780 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001781 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001782 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001783 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001784 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001785 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001786 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001787 }
1788 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1789 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001790 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001791 p = expand_string_to_string(argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001792 putenv(p);
Denis Vlasenko55789c62008-06-18 16:30:42 +00001793//FIXME: do we leak p?!
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001794 }
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00001795 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001796 if (strcmp(argv[i], x->cmd) == 0) {
1797 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001798 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001799 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001800 return EXIT_SUCCESS;
1801 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001802 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001803 /* XXX setup_redirects acts on file descriptors, not FILEs.
1804 * This is perfect for work that comes after exec().
1805 * Is it really safe for inline use? Experimentally,
1806 * things seem to work with glibc. */
1807 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001808 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001809 argv_expanded = expand_strvec_to_strvec(argv + i);
1810 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001811 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001812 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001813 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001814 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Eric Andersen25f27032001-04-26 23:22:31 +00001815 return rcode;
1816 }
1817 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001818#if ENABLE_FEATURE_SH_STANDALONE
1819 {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00001820 int a = find_applet_by_name(argv[i]);
1821 if (a >= 0 && APPLET_IS_NOFORK(a)) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001822 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001823 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001824 argv_expanded = argv + i;
Denis Vlasenko170435c2007-05-23 13:01:10 +00001825 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001826 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00001827 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001828 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001829 restore_redirects(squirrel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001830 debug_printf_exec("run_pipe return %d\n", rcode);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00001831 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001832 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001833 }
1834 }
1835#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001836 }
1837
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001838 /* Disable job control signals for shell (parent) and
1839 * for initial child code after fork */
1840 set_jobctrl_sighandler(SIG_IGN);
1841
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001842 /* Going to fork a child per each pipe member */
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001843 pi->alive_progs = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001844 nextin = 0;
1845
Eric Andersen25f27032001-04-26 23:22:31 +00001846 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00001847#if !BB_MMU
1848 char **ptrs2free = NULL;
1849#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001850 child = &(pi->progs[i]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001851 if (child->argv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001852 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001853#if !BB_MMU
1854 ptrs2free = alloc_ptrs(child->argv);
1855#endif
1856 } else
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001857 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001858
1859 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001860 pipefds[0] = 0;
1861 pipefds[1] = 1;
1862 if ((i + 1) < pi->num_progs)
1863 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001864
Denis Vlasenko05743d72008-02-10 12:10:08 +00001865 child->pid = BB_MMU ? fork() : vfork();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001866 if (!child->pid) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00001867 if (ENABLE_HUSH_JOB)
1868 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001869#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001870 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00001871 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001872 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001873 pid_t pgrp;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001874 /* Don't do pgrp restore anymore on fatal signals */
1875 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko05743d72008-02-10 12:10:08 +00001876 pgrp = pi->pgrp;
1877 if (pgrp < 0) /* true for 1st process only */
1878 pgrp = getpid();
1879 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001880 /* We do it in *every* child, not just first,
1881 * to avoid races */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001882 tcsetpgrp(interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001883 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001884 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001885#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00001886 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001887 xmove_fd(pipefds[1], 1); /* write end */
1888 if (pipefds[0] > 1)
1889 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00001890 /* Like bash, explicit redirects override pipes,
1891 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001892 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001893
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001894 /* Restore default handlers just prior to exec */
1895 set_jobctrl_sighandler(SIG_DFL);
1896 set_misc_sighandler(SIG_DFL);
1897 signal(SIGCHLD, SIG_DFL);
Denis Vlasenko76d50412008-06-10 16:19:39 +00001898 pseudo_exec(ptrs2free, child); /* does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00001899 }
Denis Vlasenko76d50412008-06-10 16:19:39 +00001900#if !BB_MMU
1901 free_strings(ptrs2free);
1902#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001903 if (child->pid < 0) { /* [v]fork failed */
1904 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001905 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001906 } else {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001907 pi->alive_progs++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001908#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001909 /* Second and next children need to know pid of first one */
1910 if (pi->pgrp < 0)
1911 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001912#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001913 }
Eric Andersen25f27032001-04-26 23:22:31 +00001914
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001915 if (i)
1916 close(nextin);
1917 if ((i + 1) < pi->num_progs)
1918 close(pipefds[1]); /* write end */
1919 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00001920 nextin = pipefds[0];
1921 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00001922
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001923 if (!pi->alive_progs) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00001924 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
1925 return 1;
1926 }
1927
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00001928 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00001929 return -1;
1930}
1931
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001932#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001933static void debug_print_tree(struct pipe *pi, int lvl)
1934{
1935 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001936 [PIPE_SEQ] = "SEQ",
1937 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001938 [PIPE_OR ] = "OR" ,
1939 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001940 };
1941 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001942 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001943#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001944 [RES_IF ] = "IF" ,
1945 [RES_THEN ] = "THEN" ,
1946 [RES_ELIF ] = "ELIF" ,
1947 [RES_ELSE ] = "ELSE" ,
1948 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001949#endif
1950#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001951 [RES_FOR ] = "FOR" ,
1952 [RES_WHILE] = "WHILE",
1953 [RES_UNTIL] = "UNTIL",
1954 [RES_DO ] = "DO" ,
1955 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001956 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001957#endif
1958 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001959 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001960 };
1961
1962 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001963
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001964 pin = 0;
1965 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001966 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1967 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001968 prn = 0;
1969 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001970 struct child_prog *child = &pi->progs[prn];
1971 char **argv = child->argv;
1972
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001973 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001974 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001975 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001976 (child->subshell ? "()" : "{}"),
1977 argv);
1978 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001979 prn++;
1980 continue;
1981 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001982 if (argv) while (*argv) {
1983 fprintf(stderr, " '%s'", *argv);
1984 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001985 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001986 fprintf(stderr, "\n");
1987 prn++;
1988 }
1989 pi = pi->next;
1990 pin++;
1991 }
1992}
1993#endif
1994
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001995/* NB: called by pseudo_exec, and therefore must not modify any
1996 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00001997static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00001998{
Denis Vlasenko06810332007-05-21 23:30:54 +00001999 struct pipe *rpipe;
2000#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002001 char *for_varname = NULL;
2002 char **for_lcur = NULL;
2003 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002004 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00002005#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002006 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002007 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002008 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00002009#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002010 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00002011#else
2012 enum { if_code = 0, next_if_code = 0 };
2013#endif
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002014 reserved_style rword IF_HAS_NO_KEYWORDS(= RES_NONE);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002015 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002016
Denis Vlasenko05743d72008-02-10 12:10:08 +00002017 debug_printf_exec("run_list start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00002018
Denis Vlasenko06810332007-05-21 23:30:54 +00002019#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002020 /* check syntax for "for" */
2021 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002022 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002023 && (rpipe->next == NULL)
2024 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002025 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002026 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002027 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002028 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002029 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
2030 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002031 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002032 /* TODO: what is tested in the first condition? */
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00002033 syntax("malformed for"); /* 2nd condition: FOR not followed by IN */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002034 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002035 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002036 }
2037 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002038#else
2039 rpipe = NULL;
2040#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002041
2042#if ENABLE_HUSH_JOB
2043 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2044 * We are saving state before entering outermost list ("while...done")
2045 * so that ctrl-Z will correctly background _entire_ outermost list,
2046 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002047 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002048 if (sigsetjmp(toplevel_jb, 1)) {
2049 /* ctrl-Z forked and we are parent; or ctrl-C.
2050 * Sighandler has longjmped us here */
2051 signal(SIGINT, SIG_IGN);
2052 signal(SIGTSTP, SIG_IGN);
2053 /* Restore level (we can be coming from deep inside
2054 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002055 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002056#if ENABLE_FEATURE_SH_STANDALONE
2057 if (nofork_save.saved) { /* if save area is valid */
2058 debug_printf_jobs("exiting nofork early\n");
2059 restore_nofork_data(&nofork_save);
2060 }
2061#endif
2062 if (ctrl_z_flag) {
2063 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2064 * Remember this child as background job */
2065 insert_bg_job(pi);
2066 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002067 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002068 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002069 }
2070 rcode = 0;
2071 goto ret;
2072 }
2073 /* ctrl-Z handler will store pid etc in pi */
2074 toplevel_list = pi;
2075 ctrl_z_flag = 0;
2076#if ENABLE_FEATURE_SH_STANDALONE
2077 nofork_save.saved = 0; /* in case we will run a nofork later */
2078#endif
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00002079 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002080 signal(SIGINT, handler_ctrl_c);
2081 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00002082#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002083
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002084 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002085 IF_HAS_KEYWORDS(rword = pi->res_word;)
2086 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
Denis Vlasenko06810332007-05-21 23:30:54 +00002087#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002088 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002089 flag_restore = 0;
2090 if (!rpipe) {
2091 flag_rep = 0;
2092 rpipe = pi;
2093 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002094 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002095#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002096 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2097 rword, if_code, next_if_code, skip_more_for_this_rword);
2098 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002099 if (pi->followup == PIPE_SEQ)
2100 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002101 continue;
2102 }
2103 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002104 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002105#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002106 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002107 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002108 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002109 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002110 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002111 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002112 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002113 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002114#endif
2115#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002116 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002117 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002118 /* first loop through for */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002119 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002120 if (!pi->next->progs->argv)
2121 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002122 /* create list of variable values */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002123 debug_print_strings("for_list made from", pi->next->progs->argv);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002124 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002125 debug_print_strings("for_list", for_list);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002126 for_lcur = for_list;
2127 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002128 pi->progs->argv[0] = NULL;
2129 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002130 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002131 free(pi->progs->argv[0]);
2132 if (!*for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002133 /* for loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002134 free(for_list);
2135 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002136 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002137 pi->progs->argv[0] = for_varname;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002138 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002139 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002140 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002141 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002142 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002143 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002144 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002145 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002146 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002147 if (!flag_rep)
2148 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002149 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002150 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002151 if (flag_rep) {
2152 flag_restore = 1;
2153 } else {
2154 rpipe = NULL;
2155 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002156 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002157#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002158 if (pi->num_progs == 0)
2159 continue;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002160 debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
2161 rcode = run_pipe(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002162 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002163 /* We only ran a builtin: rcode was set by the return value
Denis Vlasenko05743d72008-02-10 12:10:08 +00002164 * of run_pipe(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002165 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002166 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002167 /* Even bash 3.2 doesn't do that well with nested bg:
2168 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002169 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002170#if ENABLE_HUSH_JOB
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002171 if (run_list_level == 1)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002172 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002173#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002174 rcode = EXIT_SUCCESS;
2175 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002176#if ENABLE_HUSH_JOB
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002177 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002178 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002179 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002180 } else
2181#endif
2182 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002183 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002184 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002185 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002186 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002187 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002188 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002189 last_return_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00002190#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002191 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002192 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002193#endif
2194#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002195 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002196 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002197 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002198 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002199#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002200 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2201 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2202 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002203 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002204 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002205 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002206 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002207
2208#if ENABLE_HUSH_JOB
2209 if (ctrl_z_flag) {
2210 /* ctrl-Z forked somewhere in the past, we are the child,
2211 * and now we completed running the list. Exit. */
2212 exit(rcode);
2213 }
2214 ret:
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002215 if (!--run_list_level && interactive_fd) {
2216 signal(SIGTSTP, SIG_IGN);
2217 signal(SIGINT, SIG_IGN);
2218 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002219#endif
Denis Vlasenko05743d72008-02-10 12:10:08 +00002220 debug_printf_exec("run_list lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002221 return rcode;
2222}
2223
Eric Andersen25f27032001-04-26 23:22:31 +00002224/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002225static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002226{
2227 char **p;
2228 struct child_prog *child;
2229 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002230 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002231
2232 if (pi->stopped_progs > 0)
2233 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002234 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002235 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002236 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002237 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002238 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002239 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002240 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002241 }
Denis Vlasenkof962a032007-11-23 12:50:54 +00002242 free_strings(child->argv);
2243 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002244 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002245 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002246 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002247 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002248 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002249 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002250 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002251 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko211b59b2008-06-23 16:28:53 +00002252 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002253 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002254 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002255 if (r->rd_filename) {
2256 debug_printf_clean(" %s\n", r->rd_filename);
2257 free(r->rd_filename);
2258 r->rd_filename = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002259 }
Eric Andersen25f27032001-04-26 23:22:31 +00002260 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002261 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002262 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002263 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002264 free(r);
2265 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002266 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002267 }
2268 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002269 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002270#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002271 free(pi->cmdtext);
2272 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002273#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002274 return ret_code;
2275}
2276
Eric Andersenbf7df042001-05-23 22:18:35 +00002277static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002278{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002279 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002280 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002281
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002282 for (pi = head; pi; pi = next) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002283#if HAS_KEYWORDS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002284 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002285#endif
Eric Andersenbf7df042001-05-23 22:18:35 +00002286 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002287 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002288 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002289 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002290 free(pi);
2291 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002292 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002293}
2294
2295/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002296static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002297{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002298 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002299 debug_printf_exec("run_and_free_list entered\n");
2300 if (!fake_mode) {
2301 debug_printf_exec(": run_list with %d members\n", pi->num_progs);
2302 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002303 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002304 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00002305 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002306 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002307 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002308 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002309 return rcode;
2310}
2311
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002312
Denis Vlasenko170435c2007-05-23 13:01:10 +00002313/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002314 * all variable references within and returns a pointer to
2315 * a list of expanded strings, possibly with larger number
2316 * of strings. (Think VAR="a b"; echo $VAR).
2317 * This new list is allocated as a single malloc block.
2318 * NULL-terminated list of char* pointers is at the beginning of it,
2319 * followed by strings themself.
2320 * Caller can deallocate entire list by single free(list). */
2321
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002322/* Store given string, finalizing the word and starting new one whenever
2323 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002324 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002325static int expand_on_ifs(o_string *output, int n, const char *str)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002326{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002327 while (1) {
2328 int word_len = strcspn(str, ifs);
2329 if (word_len) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002330 if (output->o_quote || !output->o_glob)
2331 o_addQstr(output, str, word_len);
2332 else /* protect backslashes against globbing up :) */
2333 o_addstr_duplicate_backslash(output, str, word_len);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002334 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002335 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002336 if (!*str) /* EOL - do not finalize word */
2337 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002338 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002339 debug_print_list("expand_on_ifs", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002340 n = o_save_ptr(output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002341 str += strspn(str, ifs); /* skip ifs chars */
2342 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002343 debug_print_list("expand_on_ifs[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002344 return n;
2345}
2346
2347/* Expand all variable references in given string, adding words to list[]
2348 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2349 * to be filled). This routine is extremely tricky: has to deal with
2350 * variables/parameters with whitespace, $* and $@, and constructs like
2351 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002352/* NB: another bug is that we cannot detect empty strings yet:
2353 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002354static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002355{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002356 /* or_mask is either 0 (normal case) or 0x80
Denis Vlasenko55789c62008-06-18 16:30:42 +00002357 * (expansion of right-hand side of assignment == 1-element expand.
2358 * It will also do no globbing, and thus we must not backslash-quote!) */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002359
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002360 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002361 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002362 const char *val;
2363 char *p;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002364
2365 ored_ch = 0;
2366
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002367 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002368 debug_print_list("expand_vars_to_list", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002369 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002370 debug_print_list("expand_vars_to_list[0]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002371
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002372 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002373#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002374 o_string subst_result = NULL_O_STRING;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002375#endif
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002376
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002377 o_addstr(output, arg, p - arg);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002378 debug_print_list("expand_vars_to_list[1]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002379 arg = ++p;
2380 p = strchr(p, SPECIAL_VAR_SYMBOL);
2381
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002382 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002383 ored_ch |= first_ch;
2384 val = NULL;
2385 switch (first_ch & 0x7f) {
2386 /* Highest bit in first_ch indicates that var is double-quoted */
2387 case '$': /* pid */
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00002388 val = utoa(root_pid);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002389 break;
2390 case '!': /* bg pid */
2391 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2392 break;
2393 case '?': /* exitcode */
2394 val = utoa(last_return_code);
2395 break;
2396 case '#': /* argc */
2397 val = utoa(global_argc ? global_argc-1 : 0);
2398 break;
2399 case '*':
2400 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002401 i = 1;
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002402 if (!global_argv[i])
2403 break;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002404 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002405 smallint sv = output->o_quote;
2406 /* unquoted var's contents should be globbed, so don't quote */
2407 output->o_quote = 0;
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002408 while (global_argv[i]) {
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002409 n = expand_on_ifs(output, n, global_argv[i]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002410 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002411 if (global_argv[i++][0] && global_argv[i]) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002412 /* this argv[] is not empty and not last:
2413 * put terminating NUL, start new word */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002414 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002415 debug_print_list("expand_vars_to_list[2]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002416 n = o_save_ptr(output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002417 debug_print_list("expand_vars_to_list[3]", output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002418 }
2419 }
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002420 output->o_quote = sv;
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002421 } else
2422 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002423 * and in this case should treat it like '$*' - see 'else...' below */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002424 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002425 while (1) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002426 o_addQstr(output, global_argv[i], strlen(global_argv[i]));
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002427 if (++i >= global_argc)
2428 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002429 o_addchr(output, '\0');
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002430 debug_print_list("expand_vars_to_list[4]", output, n);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002431 n = o_save_ptr(output, n);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002432 }
2433 } else { /* quoted $*: add as one word */
Denis Vlasenkoc3c66592007-11-24 00:22:42 +00002434 while (1) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002435 o_addQstr(output, global_argv[i], strlen(global_argv[i]));
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002436 if (!global_argv[++i])
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002437 break;
2438 if (ifs[0])
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002439 o_addchr(output, ifs[0]);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002440 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002441 }
2442 break;
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002443 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2444 /* "Empty variable", used to make "" etc to not disappear */
2445 arg++;
2446 ored_ch = 0x80;
2447 break;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002448#if ENABLE_HUSH_TICK
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002449 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002450 struct in_str input;
2451 *p = '\0';
2452 arg++;
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002453//TODO: can we just stuff it into "output" directly?
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002454 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002455 setup_string_in_str(&input, arg);
2456 process_command_subs(&subst_result, &input, NULL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002457 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002458 val = subst_result.data;
2459 goto store_val;
2460 }
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002461#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002462 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002463 *p = '\0';
2464 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002465 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002466 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002467 if (i < global_argc)
2468 val = global_argv[i];
Denis Vlasenko55789c62008-06-18 16:30:42 +00002469 /* else val remains NULL: $N with too big N */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002470 } else
2471 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002472 arg[0] = first_ch;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002473#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002474 store_val:
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002475#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002476 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002477 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002478 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002479 if (val) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002480 /* unquoted var's contents should be globbed, so don't quote */
2481 smallint sv = output->o_quote;
2482 output->o_quote = 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002483 n = expand_on_ifs(output, n, val);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002484 val = NULL;
Denis Vlasenko55789c62008-06-18 16:30:42 +00002485 output->o_quote = sv;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002486 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002487 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002488 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002489 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002490 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002491 if (val) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002492 o_addQstr(output, val, strlen(val));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00002493 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002494
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002495#if ENABLE_HUSH_TICK
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002496 o_free(&subst_result);
Denis Vlasenkoccce59d2008-06-16 14:35:57 +00002497#endif
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002498 arg = ++p;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002499 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2500
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002501 if (arg[0]) {
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002502 debug_print_list("expand_vars_to_list[a]", output, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002503 /* this part is literal, and it was already pre-quoted
2504 * if needed (much earlier), do not use o_addQstr here! */
2505 o_addstr(output, arg, strlen(arg) + 1);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002506 debug_print_list("expand_vars_to_list[b]", output, n);
Denis Vlasenko2e76c3f2008-06-10 18:27:50 +00002507 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2508 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2509 ) {
2510 n--;
2511 /* allow to reuse list[n] later without re-growth */
2512 output->has_empty_slot = 1;
2513 } else {
2514 o_addchr(output, '\0');
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002515 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002516 return n;
2517}
2518
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002519static char **expand_variables(char **argv, int or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002520{
2521 int n;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00002522 char **list;
2523 char **v;
2524 o_string output = NULL_O_STRING;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002525
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002526 if (or_mask & 0x100) {
Denis Vlasenko324a3fd2008-06-18 17:49:58 +00002527 output.o_quote = 1; /* protect against globbing for "$var" */
2528 /* (unquoted $var will temporarily switch it off) */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002529 output.o_glob = 1;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00002530 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002531
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002532 n = 0;
2533 v = argv;
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002534 while (*v) {
2535 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2536 v++;
2537 }
2538 debug_print_list("expand_variables", &output, n);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002539
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002540 /* output.data (malloced in one block) gets returned in "list" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00002541 list = o_finalize_list(&output, n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002542 debug_print_strings("expand_variables[1]", list);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002543 return list;
2544}
2545
Denis Vlasenko170435c2007-05-23 13:01:10 +00002546static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002547{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002548 return expand_variables(argv, 0x100);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002549}
2550
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002551/* Used for expansion of right hand of assignments */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00002552/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2553 * "v=/bin/c*" */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002554static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002555{
2556 char *argv[2], **list;
2557
2558 argv[0] = (char*)str;
2559 argv[1] = NULL;
2560 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002561 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002562 if (!list[0] || list[1])
2563 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002564 /* actually, just move string 2*sizeof(char*) bytes back */
2565 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002566 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2567 return (char*)list;
2568}
2569
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002570/* Used for "eval" builtin */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002571static char* expand_strvec_to_string(char **argv)
2572{
2573 char **list;
2574
2575 list = expand_variables(argv, 0x80);
2576 /* Convert all NULs to spaces */
2577 if (list[0]) {
2578 int n = 1;
2579 while (list[n]) {
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002580 if (HUSH_DEBUG)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002581 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2582 bb_error_msg_and_die("BUG in varexp3");
2583 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2584 n++;
2585 }
2586 }
2587 strcpy((char*)list, list[0]);
2588 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002589 return (char*)list;
2590}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002591
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002592
2593/* Used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002594static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002595{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002596 struct variable *cur;
2597 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002598
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002599 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002600 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002601 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002602 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002603 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002604 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002605 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002606 return NULL;
2607}
2608
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002609/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002610 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002611static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002612{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002613 struct variable *cur;
2614 char *value;
2615 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002616
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002617 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002618 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002619 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002620 return -1;
2621 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002622
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002623 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002624 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2625 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002626 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002627 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002628 /* Bail out. Note that now cur points
2629 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002630 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002631 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002632 cur = cur->next;
2633 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002634 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002635 /* We found an existing var with this name */
2636 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002637 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002638 bb_error_msg("%s: readonly variable", str);
2639 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002640 return -1;
2641 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002642 unsetenv(str); /* just in case */
2643 *value = '=';
2644 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002645 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002646 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002647 goto exp;
2648 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002649 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002650 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002651 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002652 goto free_and_exp;
2653 }
2654 /* max_len == 0 signifies "malloced" var, which we can
2655 * (and has to) free */
2656 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002657 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002658 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002659 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002660 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002661
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002662 /* Not found - create next variable struct */
2663 cur->next = xzalloc(sizeof(*cur));
2664 cur = cur->next;
2665
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002666 set_str_and_exp:
2667 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002668 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002669 if (flg_export)
2670 cur->flg_export = 1;
2671 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002672 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002673 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002674}
2675
Eric Andersenf72f5622001-05-15 23:21:41 +00002676static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002677{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002678 struct variable *cur;
2679 struct variable *prev = prev; /* for gcc */
2680 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002681
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002682 if (!name)
2683 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002684 name_len = strlen(name);
2685 cur = top_var;
2686 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002687 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002688 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002689 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002690 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002691 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002692 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2693 * is ro, and we cannot reach this code on the 1st pass */
2694 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002695 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002696 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002697 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002698 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002699 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002700 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002701 prev = cur;
2702 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002703 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002704}
2705
Eric Andersen25f27032001-04-26 23:22:31 +00002706/* the src parameter allows us to peek forward to a possible &n syntax
2707 * for file descriptor duplication, e.g., "2>&1".
2708 * Return code is 0 normally, 1 if a syntax error is detected in src.
2709 * Resource errors (in xmalloc) cause the process to exit */
2710static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2711 struct in_str *input)
2712{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002713 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002714 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002715 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002716
2717 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002718 while (redir) {
2719 last_redir = redir;
2720 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002721 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002722 redir = xzalloc(sizeof(struct redir_struct));
2723 /* redir->next = NULL; */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002724 /* redir->rd_filename = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002725 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002726 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002727 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002728 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002729 }
2730
Denis Vlasenko55789c62008-06-18 16:30:42 +00002731 redir->rd_type = style;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002732 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002733
2734 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2735
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002736 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002737 redir->dup = redirect_dup_num(input);
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002738 if (redir->dup == -2)
2739 return 1; /* syntax error */
Eric Andersen25f27032001-04-26 23:22:31 +00002740 if (redir->dup != -1) {
2741 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002742 * is legit; I postpone that to "run time"
2743 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002744 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2745 } else {
2746 /* We do _not_ try to open the file that src points to,
2747 * since we need to return and let src be expanded first.
2748 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002749 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002750 ctx->pending_redirect = redir;
2751 }
2752 return 0;
2753}
2754
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002755static struct pipe *new_pipe(void)
2756{
Eric Andersen25f27032001-04-26 23:22:31 +00002757 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002758 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002759 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002760 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00002761 return pi;
2762}
2763
2764static void initialize_context(struct p_context *ctx)
2765{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002766 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00002767 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002768 /* Create the memory for child, roughly:
2769 * ctx->pipe->progs = new struct child_prog;
2770 * ctx->pipe->progs[0].family = ctx->pipe;
2771 * ctx->child = &ctx->pipe->progs[0];
2772 */
2773 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00002774}
2775
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002776/* If a reserved word is found and processed, parse context is modified
2777 * and 1 is returned.
2778 * Handles if, then, elif, else, fi, for, while, until, do, done.
Eric Andersen25f27032001-04-26 23:22:31 +00002779 * case, function, and select are obnoxious, save those for later.
2780 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002781#if HAS_KEYWORDS
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002782static int reserved_word(const o_string *word, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002783{
2784 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002785 char literal[7];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002786 unsigned char res;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002787 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002788 };
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002789 enum {
2790 FLAG_END = (1 << RES_NONE ),
2791#if ENABLE_HUSH_IF
2792 FLAG_IF = (1 << RES_IF ),
2793 FLAG_THEN = (1 << RES_THEN ),
2794 FLAG_ELIF = (1 << RES_ELIF ),
2795 FLAG_ELSE = (1 << RES_ELSE ),
2796 FLAG_FI = (1 << RES_FI ),
2797#endif
2798#if ENABLE_HUSH_LOOPS
2799 FLAG_FOR = (1 << RES_FOR ),
2800 FLAG_WHILE = (1 << RES_WHILE),
2801 FLAG_UNTIL = (1 << RES_UNTIL),
2802 FLAG_DO = (1 << RES_DO ),
2803 FLAG_DONE = (1 << RES_DONE ),
2804 FLAG_IN = (1 << RES_IN ),
2805#endif
2806 FLAG_START = (1 << RES_XXXX ),
2807 };
Eric Andersen25f27032001-04-26 23:22:31 +00002808 /* Mostly a list of accepted follow-up reserved words.
2809 * FLAG_END means we are done with the sequence, and are ready
2810 * to turn the compound list into a command.
2811 * FLAG_START means the word must start a new compound list.
2812 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002813 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002814#if ENABLE_HUSH_IF
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002815 { "!", RES_NONE, 0 },
Eric Andersen25f27032001-04-26 23:22:31 +00002816 { "if", RES_IF, FLAG_THEN | FLAG_START },
2817 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2818 { "elif", RES_ELIF, FLAG_THEN },
2819 { "else", RES_ELSE, FLAG_FI },
2820 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002821#endif
2822#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002823 { "for", RES_FOR, FLAG_IN | FLAG_START },
2824 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2825 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002826 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002827 { "do", RES_DO, FLAG_DONE },
2828 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002829#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002830 };
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002831
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002832 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002833
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002834 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002835 if (strcmp(word->data, r->literal) != 0)
Denis Vlasenko1a735862007-05-23 00:32:25 +00002836 continue;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002837 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
2838 if (r->flag == 0) { /* '!' */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002839#if ENABLE_HUSH_LOOPS
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002840 if (ctx->ctx_res_w == RES_IN) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002841 /* 'for a in ! a b c; ...' - ! isn't a keyword here */
2842 break;
2843 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002844#endif
2845 if (ctx->ctx_inverted /* bash doesn't accept '! ! true' */
2846#if ENABLE_HUSH_LOOPS
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002847 || ctx->ctx_res_w == RES_FOR /* example: 'for ! a' */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002848#endif
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002849 ) {
2850 syntax(NULL);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002851 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002852 }
2853 ctx->ctx_inverted = 1;
2854 return 1;
2855 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002856 if (r->flag & FLAG_START) {
2857 struct p_context *new;
2858 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002859#if ENABLE_HUSH_LOOPS
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002860 if (ctx->ctx_res_w == RES_IN || ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002861 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002862 ctx->ctx_res_w = RES_SNTX;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002863 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002864 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002865#endif
2866 new = xmalloc(sizeof(*new));
2867 *new = *ctx; /* physical copy */
2868 initialize_context(ctx);
2869 ctx->stack = new;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002870 } else if (ctx->ctx_res_w == RES_NONE || !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002871 syntax(NULL);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002872 ctx->ctx_res_w = RES_SNTX;
Eric Andersen25f27032001-04-26 23:22:31 +00002873 return 1;
2874 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002875 ctx->ctx_res_w = r->res;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002876 ctx->old_flag = r->flag;
2877 if (ctx->old_flag & FLAG_END) {
2878 struct p_context *old;
2879 debug_printf("pop stack\n");
2880 done_pipe(ctx, PIPE_SEQ);
2881 old = ctx->stack;
2882 old->child->group = ctx->list_head;
2883 old->child->subshell = 0;
2884 *ctx = *old; /* physical copy */
2885 free(old);
2886 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002887 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002888 }
2889 return 0;
2890}
Denis Vlasenko06810332007-05-21 23:30:54 +00002891#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002892
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002893/* Word is complete, look at it and update parsing context.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002894 * Normal return is 0. Syntax errors return 1. */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002895static int done_word(o_string *word, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002896{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002897 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002898
Denis Vlasenko55789c62008-06-18 16:30:42 +00002899 /* If this word wasn't an assignment, next ones definitely
2900 * can't be assignments. Even if they look like ones. */
2901 if (word->o_assignment != DEFINITELY_ASSIGNMENT) {
2902 word->o_assignment = NOT_ASSIGNMENT;
2903 } else {
2904 word->o_assignment = MAYBE_ASSIGNMENT;
2905 }
2906
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002907 debug_printf_parse("done_word entered: '%s' %p\n", word->data, child);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002908 if (word->length == 0 && word->nonnull == 0) {
2909 debug_printf_parse("done_word return 0: true null, ignored\n");
2910 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002911 }
2912 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002913 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
2914 * only if run as "bash", not "sh" */
2915 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002916 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002917 debug_printf("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00002918 } else {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002919 if (child->group) { /* TODO: example how to trigger? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002920 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002921 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2922 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002923 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002924#if HAS_KEYWORDS
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002925 if (!child->argv) { /* if it's the first word... */
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002926 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
2927 if (reserved_word(word, ctx)) {
2928 o_reset(word);
Denis Vlasenko55789c62008-06-18 16:30:42 +00002929 word->o_assignment = NOT_ASSIGNMENT;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002930 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
2931 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002932 }
Eric Andersen25f27032001-04-26 23:22:31 +00002933 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002934#endif
Denis Vlasenko55789c62008-06-18 16:30:42 +00002935 if (word->nonnull /* we saw "xx" or 'xx' */
2936 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
2937 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
2938 /* (otherwise it's "abc".... and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002939 ) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00002940 /* Insert "empty variable" reference, this makes
2941 * e.g. "", $empty"" etc to not disappear */
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00002942 o_addchr(word, SPECIAL_VAR_SYMBOL);
2943 o_addchr(word, SPECIAL_VAR_SYMBOL);
2944 }
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002945 child->argv = add_malloced_string_to_strings(child->argv, xstrdup(word->data));
2946 debug_print_strings("word appended to argv", child->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002947 }
Eric Andersen25f27032001-04-26 23:22:31 +00002948
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002949 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002950 ctx->pending_redirect = NULL;
2951
Denis Vlasenko06810332007-05-21 23:30:54 +00002952#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002953 /* Force FOR to have just one word (variable name) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002954 if (ctx->ctx_res_w == RES_FOR)
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002955 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko06810332007-05-21 23:30:54 +00002956#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002957 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002958 return 0;
2959}
2960
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00002961/* Command (member of a pipe) is complete. The only possible error here
2962 * is out of memory, in which case xmalloc exits. */
Eric Andersen25f27032001-04-26 23:22:31 +00002963static int done_command(struct p_context *ctx)
2964{
2965 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002966 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002967 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002968 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002969
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002970 if (child) {
2971 if (child->group == NULL
2972 && child->argv == NULL
2973 && child->redirects == NULL
2974 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002975 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2976 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002977 }
Eric Andersen25f27032001-04-26 23:22:31 +00002978 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002979 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002980 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002981 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002982 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002983
2984 /* Only real trickiness here is that the uncommitted
2985 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00002986 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002987 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00002988
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002989 memset(child, 0, sizeof(*child));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002990 child->family = pi;
Eric Andersen25f27032001-04-26 23:22:31 +00002991
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002992 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00002993 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002994
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002995 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00002996}
2997
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002998static void done_pipe(struct p_context *ctx, pipe_style type)
Eric Andersen25f27032001-04-26 23:22:31 +00002999{
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003000 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003001
3002 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003003 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003004 ctx->pipe->followup = type;
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003005 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3006 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3007 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003008 /* Without this check, even just <enter> on command line generates
3009 * tree of three NOPs (!). Which is harmless but annoying.
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003010 * IOW: it is safe to do it unconditionally.
3011 * RES_IN case is for "for a in; do ..." (empty IN set)
3012 * to work. */
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00003013 if (not_null USE_HUSH_LOOPS(|| ctx->pipe->res_word == RES_IN)) {
Denis Vlasenko6eaf8de2008-06-17 12:09:21 +00003014 struct pipe *new_p = new_pipe();
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003015 ctx->pipe->next = new_p;
3016 ctx->pipe = new_p;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003017 ctx->child = NULL; /* needed! */
3018 /* Create the memory for child, roughly:
3019 * ctx->pipe->progs = new struct child_prog;
3020 * ctx->pipe->progs[0].family = ctx->pipe;
Denis Vlasenko7049ff82008-06-25 09:53:17 +00003021 * ctx->child = &ctx->pipe->progs[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003022 */
3023 done_command(ctx);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003024 }
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003025 debug_printf_parse("done_pipe return\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003026}
3027
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003028/* Peek ahead in the in_str to find out if we have a "&n" construct,
Eric Andersen25f27032001-04-26 23:22:31 +00003029 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003030 * Return either -2 (syntax error), -1 (no &), or the number found.
Eric Andersen25f27032001-04-26 23:22:31 +00003031 */
3032static int redirect_dup_num(struct in_str *input)
3033{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003034 int ch, d = 0, ok = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003035 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003036 if (ch != '&') return -1;
3037
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003038 i_getch(input); /* get the & */
3039 ch = i_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003040 if (ch == '-') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003041 i_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003042 return -3; /* "-" represents "close me" */
3043 }
3044 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003045 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003046 ok = 1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003047 i_getch(input);
3048 ch = i_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003049 }
3050 if (ok) return d;
3051
Manuel Novoa III cad53642003-03-19 09:13:01 +00003052 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003053 return -2;
3054}
3055
3056/* If a redirect is immediately preceded by a number, that number is
3057 * supposed to tell which file descriptor to redirect. This routine
3058 * looks for such preceding numbers. In an ideal world this routine
3059 * needs to handle all the following classes of redirects...
3060 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3061 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3062 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3063 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3064 * A -1 output from this program means no valid number was found, so the
3065 * caller should use the appropriate default for this redirection.
3066 */
3067static int redirect_opt_num(o_string *o)
3068{
3069 int num;
3070
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003071 if (o->length == 0)
3072 return -1;
3073 for (num = 0; num < o->length; num++) {
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003074 if (!isdigit(o->data[num])) {
Eric Andersen25f27032001-04-26 23:22:31 +00003075 return -1;
3076 }
3077 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003078 num = atoi(o->data);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003079 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00003080 return num;
3081}
3082
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003083#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003084static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003085{
3086 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003087 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003088
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003089 xpipe(channel);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003090/* *** NOMMU WARNING *** */
3091/* By using vfork here, we suspend parent till child exits or execs.
3092 * If child will not do it before it fills the pipe, it can block forever
3093 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
Denis Vlasenko3fe4f982008-06-09 16:02:39 +00003094 * Try this script:
3095 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3096 * huge=`cat TESTFILE` # will block here forever
3097 * echo OK
Denis Vlasenko05743d72008-02-10 12:10:08 +00003098 */
3099 pid = BB_MMU ? fork() : vfork();
3100 if (pid < 0)
3101 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3102 if (pid == 0) { /* child */
Denis Vlasenko83177992008-02-11 08:44:36 +00003103 if (ENABLE_HUSH_JOB)
3104 die_sleep = 0; /* let nofork's xfuncs die */
Denis Vlasenko284d0fa2008-02-16 13:18:17 +00003105 close(channel[0]); /* NB: close _first_, then move fd! */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003106 xmove_fd(channel[1], 1);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003107 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003108#if ENABLE_HUSH_JOB
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003109 run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003110#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003111 /* Process substitution is not considered to be usual
3112 * 'command execution'.
3113 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3114 /* Not needed, we are relying on it being disabled
3115 * everywhere outside actual command execution. */
3116 /*set_jobctrl_sighandler(SIG_IGN);*/
3117 set_misc_sighandler(SIG_DFL);
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003118 /* Freeing 'head' here would break NOMMU. */
3119 _exit(run_list(head));
Eric Andersen25f27032001-04-26 23:22:31 +00003120 }
Eric Andersen25f27032001-04-26 23:22:31 +00003121 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003122 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003123 return pf;
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003124 /* 'head' is freed by the caller */
Eric Andersen25f27032001-04-26 23:22:31 +00003125}
3126
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003127/* Return code is exit status of the process that is run. */
Denis Vlasenko68404f12008-03-17 09:00:54 +00003128static int process_command_subs(o_string *dest,
Denis Vlasenko68404f12008-03-17 09:00:54 +00003129 struct in_str *input,
3130 const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003131{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003132 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003133 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003134 struct p_context inner;
3135 FILE *p;
3136 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003137
Eric Andersen25f27032001-04-26 23:22:31 +00003138 initialize_context(&inner);
3139
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003140 /* Recursion to generate command */
Eric Andersen25f27032001-04-26 23:22:31 +00003141 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003142 if (retcode != 0)
3143 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003144 done_word(&result, &inner);
3145 done_pipe(&inner, PIPE_SEQ);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003146 o_free(&result);
Eric Andersen25f27032001-04-26 23:22:31 +00003147
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003148 p = generate_stream_from_list(inner.list_head);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003149 if (p == NULL)
3150 return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003151 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003152 setup_file_in_str(&pipe_str, p);
3153
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003154 /* Now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003155 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003156 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003157 if (ch == '\n') {
3158 eol_cnt++;
3159 continue;
3160 }
3161 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003162 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003163 eol_cnt--;
3164 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00003165// /* Even unquoted `echo '\'` results in two backslashes
3166// * (which are converted into one by globbing later) */
3167// if (!dest->o_quote && ch == '\\') {
3168// o_addchr(dest, ch);
3169// }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003170 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003171 }
3172
3173 debug_printf("done reading from pipe, pclose()ing\n");
3174 /* This is the step that wait()s for the child. Should be pretty
3175 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003176 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003177 * at the same time. That would be a lot of work, and contrary
3178 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003179 retcode = fclose(p);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003180 free_pipe_list(inner.list_head, /* indent: */ 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003181 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003182 return retcode;
3183}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003184#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003185
3186static int parse_group(o_string *dest, struct p_context *ctx,
3187 struct in_str *input, int ch)
3188{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003189 int rcode;
3190 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003191 struct p_context sub;
3192 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003193
3194 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003195 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003196 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003197 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3198 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003199 }
3200 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003201 endch = "}";
3202 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003203 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003204 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003205 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003206 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003207 if (rcode == 0) {
3208 done_word(dest, &sub); /* finish off the final word in the subcontext */
3209 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3210 child->group = sub.list_head;
3211 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003212 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003213 return rcode;
3214 /* child remains "open", available for possible redirects */
3215}
3216
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003217/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003218 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003219static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003220{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003221 struct variable *var = get_local_var(src);
3222 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003223 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003224 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003225}
3226
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003227#if ENABLE_HUSH_TICK
3228/* Subroutines for copying $(...) and `...` things */
3229static void add_till_backquote(o_string *dest, struct in_str *input);
3230/* '...' */
3231static void add_till_single_quote(o_string *dest, struct in_str *input)
3232{
3233 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003234 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003235 if (ch == EOF)
3236 break;
3237 if (ch == '\'')
3238 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003239 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003240 }
3241}
3242/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3243static void add_till_double_quote(o_string *dest, struct in_str *input)
3244{
3245 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003246 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003247 if (ch == '"')
3248 break;
3249 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003250 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003251 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003252 }
3253 if (ch == EOF)
3254 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003255 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003256 if (ch == '`') {
3257 add_till_backquote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003258 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003259 continue;
3260 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00003261 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003262 }
3263}
3264/* Process `cmd` - copy contents until "`" is seen. Complicated by
3265 * \` quoting.
3266 * "Within the backquoted style of command substitution, backslash
3267 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3268 * The search for the matching backquote shall be satisfied by the first
3269 * backquote found without a preceding backslash; during this search,
3270 * if a non-escaped backquote is encountered within a shell comment,
3271 * a here-document, an embedded command substitution of the $(command)
3272 * form, or a quoted string, undefined results occur. A single-quoted
3273 * or double-quoted string that begins, but does not end, within the
3274 * "`...`" sequence produces undefined results."
3275 * Example Output
3276 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3277 */
3278static void add_till_backquote(o_string *dest, struct in_str *input)
3279{
3280 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003281 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003282 if (ch == '`')
3283 break;
3284 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003285 int ch2 = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003286 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003287 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003288 ch = ch2;
3289 }
3290 if (ch == EOF)
3291 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003292 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003293 }
3294}
3295/* Process $(cmd) - copy contents until ")" is seen. Complicated by
3296 * quoting and nested ()s.
3297 * "With the $(command) style of command substitution, all characters
3298 * following the open parenthesis to the matching closing parenthesis
3299 * constitute the command. Any valid shell script can be used for command,
3300 * except a script consisting solely of redirections which produces
3301 * unspecified results."
3302 * Example Output
3303 * echo $(echo '(TEST)' BEST) (TEST) BEST
3304 * echo $(echo 'TEST)' BEST) TEST) BEST
3305 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3306 */
3307static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3308{
3309 int count = 0;
3310 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003311 int ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003312 if (ch == EOF)
3313 break;
3314 if (ch == '(')
3315 count++;
3316 if (ch == ')')
3317 if (--count < 0)
3318 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003319 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003320 if (ch == '\'') {
3321 add_till_single_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003322 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003323 continue;
3324 }
3325 if (ch == '"') {
3326 add_till_double_quote(dest, input);
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003327 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003328 continue;
3329 }
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003330 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3331 ch = i_getch(input);
3332 if (ch == EOF)
3333 break;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00003334 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003335 continue;
3336 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003337 }
3338}
3339#endif /* ENABLE_HUSH_TICK */
3340
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003341/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003342static int handle_dollar(o_string *dest, struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00003343{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003344 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003345 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003346
3347 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003348 if (isalpha(ch)) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003349 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003350 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003351 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003352 i_getch(input);
3353 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003354 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003355 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003356 if (!isalnum(ch) && ch != '_')
3357 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003358 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003359 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003360 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003361 make_one_char_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003362 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003363 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003364 i_getch(input);
3365 o_addchr(dest, ch | quote_mask);
3366 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003367 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003368 case '$': /* pid */
3369 case '!': /* last bg pid */
3370 case '?': /* last exit code */
3371 case '#': /* number of args */
3372 case '*': /* args */
3373 case '@': /* args */
3374 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003375 case '{':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003376 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3377 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003378 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003379 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003380 ch = i_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003381 if (ch == '}')
3382 break;
3383 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003384 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003385 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3386 return 1;
3387 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003388 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003389 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003390 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003391 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003392 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003393 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003394#if ENABLE_HUSH_TICK
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003395 case '(': {
3396 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003397 i_getch(input);
3398 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3399 o_addchr(dest, quote_mask | '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003400 add_till_closing_curly_brace(dest, input);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003401 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003402 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003403 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00003404 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003405#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003406 case '-':
3407 case '_':
3408 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003409 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003410 return 1;
3411 break;
3412 default:
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003413 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00003414 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003415 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003416 return 0;
3417}
3418
Denis Vlasenko55789c62008-06-18 16:30:42 +00003419/* Scan input, call done_word() whenever full IFS delemited word was seen.
3420 * call done_pipe if '\n' was seen (and end_trigger != NULL)
3421 * Return if (non-quoted) char in end_trigger was seen; or on parse error. */
3422/* Return code is 0 if end_trigger char is met,
3423 * -1 on EOF (but if end_trigger == NULL then return 0)
3424 * 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003425static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003426 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003427{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003428 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003429 int redir_fd;
3430 redir_type redir_style;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003431 int shadow_quote = dest->o_quote;
Eric Andersen25f27032001-04-26 23:22:31 +00003432 int next;
3433
Denis Vlasenkoff097622007-10-01 10:00:45 +00003434 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003435 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003436 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003437
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003438 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3439
Denis Vlasenko1a735862007-05-23 00:32:25 +00003440 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003441 m = CHAR_IFS;
3442 next = '\0';
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003443 ch = i_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003444 if (ch != EOF) {
3445 m = charmap[ch];
Denis Vlasenko55789c62008-06-18 16:30:42 +00003446 if (ch != '\n') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003447 next = i_peek(input);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003448 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003449 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003450 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003451 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003452 if (m == CHAR_ORDINARY
Denis Vlasenko55789c62008-06-18 16:30:42 +00003453 || (m != CHAR_SPECIAL && shadow_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003454 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003455 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003456 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003457 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3458 return 1;
3459 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003460 o_addQchr(dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003461 if (dest->o_assignment == MAYBE_ASSIGNMENT
3462 && ch == '='
3463 && is_assignment(dest->data)
3464 ) {
3465 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3466 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003467 continue;
3468 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003469 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003470 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003471 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003472 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003473 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003474 if (ch == EOF)
3475 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003476 /* If we aren't performing a substitution, treat
3477 * a newline as a command separator.
3478 * [why we don't handle it exactly like ';'? --vda] */
3479 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003480 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003481 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003482 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003483 if (end_trigger) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00003484 if (!shadow_quote && strchr(end_trigger, ch)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003485 /* Special case: (...word) makes last word terminate,
3486 * as if ';' is seen */
3487 if (ch == ')') {
3488 done_word(dest, ctx);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003489//err chk?
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003490 done_pipe(ctx, PIPE_SEQ);
3491 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003492 if (!HAS_KEYWORDS IF_HAS_KEYWORDS(|| ctx->ctx_res_w == RES_NONE)) {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003493 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3494 return 0;
3495 }
3496 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003497 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003498 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003499 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003500
3501 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3502 /* ch is a special char and thus this word
3503 * cannot be an assignment: */
3504 dest->o_assignment = NOT_ASSIGNMENT;
3505 }
3506
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003507 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003508 case '#':
Denis Vlasenko55789c62008-06-18 16:30:42 +00003509 if (dest->length == 0 && !shadow_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003510 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003511 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003512 if (ch == EOF || ch == '\n')
3513 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003514 i_getch(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003515 }
Eric Andersen25f27032001-04-26 23:22:31 +00003516 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003517 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003518 }
3519 break;
3520 case '\\':
3521 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003522 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003523 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003524 return 1;
3525 }
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003526 /* bash:
3527 * "The backslash retains its special meaning [in "..."]
3528 * only when followed by one of the following characters:
3529 * $, `, ", \, or <newline>. A double quote may be quoted
3530 * within double quotes by preceding it with a backslash.
3531 * If enabled, history expansion will be performed unless
3532 * an ! appearing in double quotes is escaped using
3533 * a backslash. The backslash preceding the ! is not removed."
3534 */
Denis Vlasenko55789c62008-06-18 16:30:42 +00003535 if (shadow_quote) { //NOT SURE dest->o_quote) {
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003536 if (strchr("$`\"\\", next) != NULL) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003537 o_addqchr(dest, i_getch(input));
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003538 } else {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00003539 o_addqchr(dest, '\\');
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003540 }
3541 } else {
3542 o_addchr(dest, '\\');
3543 o_addchr(dest, i_getch(input));
3544 }
Eric Andersen25f27032001-04-26 23:22:31 +00003545 break;
3546 case '$':
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003547 if (handle_dollar(dest, input) != 0) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003548 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3549 return 1;
3550 }
Eric Andersen25f27032001-04-26 23:22:31 +00003551 break;
3552 case '\'':
3553 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003554 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003555 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003556 if (ch == EOF) {
3557 syntax("unterminated '");
3558 debug_printf_parse("parse_stream return 1: unterminated '\n");
3559 return 1;
3560 }
3561 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003562 break;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003563 if (dest->o_assignment == NOT_ASSIGNMENT)
3564 o_addqchr(dest, ch);
3565 else
3566 o_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003567 }
Eric Andersen25f27032001-04-26 23:22:31 +00003568 break;
3569 case '"':
3570 dest->nonnull = 1;
Denis Vlasenko55789c62008-06-18 16:30:42 +00003571 shadow_quote ^= 1; /* invert */
3572 if (dest->o_assignment == NOT_ASSIGNMENT)
3573 dest->o_quote ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003574 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003575#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003576 case '`': {
3577 //int pos = dest->length;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003578 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko55789c62008-06-18 16:30:42 +00003579 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003580 add_till_backquote(dest, input);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003581 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00003582 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00003583 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00003584 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003585#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003586 case '>':
3587 redir_fd = redirect_opt_num(dest);
3588 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003589 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003590 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003591 redir_style = REDIRECT_APPEND;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003592 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003593 }
3594#if 0
3595 else if (next == '(') {
3596 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003597 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003598 return 1;
3599 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003600#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003601 setup_redirect(ctx, redir_fd, redir_style, input);
3602 break;
3603 case '<':
3604 redir_fd = redirect_opt_num(dest);
3605 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003606 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003607 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003608 redir_style = REDIRECT_HEREIS;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003609 i_getch(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003610 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003611 redir_style = REDIRECT_IO;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003612 i_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003613 }
3614#if 0
3615 else if (next == '(') {
3616 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003617 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003618 return 1;
3619 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003620#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003621 setup_redirect(ctx, redir_fd, redir_style, input);
3622 break;
3623 case ';':
3624 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003625 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003626 break;
3627 case '&':
3628 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003629 if (next == '&') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003630 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003631 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003632 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003633 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003634 }
3635 break;
3636 case '|':
3637 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003638 if (next == '|') {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003639 i_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003640 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003641 } else {
3642 /* we could pick up a file descriptor choice here
3643 * with redirect_opt_num(), but bash doesn't do it.
3644 * "echo foo 2| cat" yields "foo 2". */
3645 done_command(ctx);
3646 }
3647 break;
3648 case '(':
3649 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003650 if (parse_group(dest, ctx, input, ch) != 0) {
3651 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003652 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003653 }
Eric Andersen25f27032001-04-26 23:22:31 +00003654 break;
3655 case ')':
3656 case '}':
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003657 /* proper use of this character is caught by end_trigger */
3658 syntax("unexpected } or )");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003659 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003660 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003661 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003662 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003663 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003664 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003665 } /* while (1) */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003666 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003667 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003668 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003669 return 0;
3670}
3671
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003672static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003673{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003674 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003675 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003676}
3677
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003678static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003679{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003680 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003681 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003682 if (ifs == NULL)
3683 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003684 /* Precompute a list of 'flow through' behavior so it can be treated
3685 * quickly up front. Computation is necessary because of IFS.
3686 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003687 * The charmap[] array only really needs two bits each,
3688 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003689 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003690 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003691#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003692 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003693#else
3694 set_in_charmap("\\$\"", CHAR_SPECIAL);
3695#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003696 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003697 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003698}
3699
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003700/* Most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003701 * from builtin_source() and builtin_eval() */
3702static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003703{
Eric Andersen25f27032001-04-26 23:22:31 +00003704 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003705 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003706 int rcode;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003707
Eric Andersen25f27032001-04-26 23:22:31 +00003708 do {
3709 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003710 update_charmap();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003711#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003712 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003713#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003714 /* We will stop & execute after each ';' or '\n'.
3715 * Example: "sleep 9999; echo TEST" + ctrl-C:
3716 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003717 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003718#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003719 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003720 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003721 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003722#endif
3723 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003724 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003725 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003726 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003727 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
3728 run_and_free_list(ctx.list_head);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003729 } else {
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003730 /* We arrive here also if rcode == 1 (error in parse_stream) */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003731#if HAS_KEYWORDS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003732 if (ctx.old_flag != 0) {
3733 free(ctx.stack);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003734 o_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003735 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003736#endif
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00003737 /*temp.nonnull = 0; - o_free does it below */
3738 /*temp.o_quote = 0; - o_free does it below */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003739 free_pipe_list(ctx.list_head, /* indent: */ 0);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003740 /* Discard all unprocessed line input, force prompt on */
3741 inp->p = NULL;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003742#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003743 inp->promptme = 1;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003744#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003745 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00003746 o_free(&temp);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00003747 /* loop on syntax errors, return on EOF: */
3748 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
Eric Andersen25f27032001-04-26 23:22:31 +00003749 return 0;
3750}
3751
Denis Vlasenko170435c2007-05-23 13:01:10 +00003752static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003753{
3754 struct in_str input;
3755 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003756 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003757}
3758
Denis Vlasenko170435c2007-05-23 13:01:10 +00003759static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003760{
3761 int rcode;
3762 struct in_str input;
3763 setup_file_in_str(&input, f);
Denis Vlasenko5703c222008-06-15 11:49:42 +00003764 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
Eric Andersen25f27032001-04-26 23:22:31 +00003765 return rcode;
3766}
3767
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003768#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003769/* Make sure we have a controlling tty. If we get started under a job
3770 * aware app (like bash for example), make sure we are now in charge so
3771 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003772static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003773{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003774 pid_t shell_pgrp;
3775
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003776 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003777 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003778 close_on_exec_on(interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003779
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003780 /* If we were ran as 'hush &',
3781 * sleep until we are in the foreground. */
3782 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003783 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003784 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003785 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003786 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003787
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003788 /* Ignore job-control and misc signals. */
3789 set_jobctrl_sighandler(SIG_IGN);
3790 set_misc_sighandler(SIG_IGN);
3791//huh? signal(SIGCHLD, SIG_IGN);
3792
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003793 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003794 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003795
3796 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003797 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003798 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003799 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003800}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003801#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003802
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003803
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00003804int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00003805int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003806{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00003807 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003808 static const struct variable const_shell_ver = {
3809 .next = NULL,
3810 .varstr = (char*)version_str,
3811 .max_len = 1, /* 0 can provoke free(name) */
3812 .flg_export = 1,
3813 .flg_read_only = 1,
3814 };
3815
Eric Andersen25f27032001-04-26 23:22:31 +00003816 int opt;
3817 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003818 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003819 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003820
Denis Vlasenko574f2f42008-02-27 18:41:59 +00003821 INIT_G();
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003822
Denis Vlasenko16c2fea2008-06-17 12:28:44 +00003823 root_pid = getpid();
3824
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003825 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003826 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003827 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003828 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3829 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003830 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003831 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003832 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003833 if (e) while (*e) {
3834 char *value = strchr(*e, '=');
3835 if (value) { /* paranoia */
3836 cur_var->next = xzalloc(sizeof(*cur_var));
3837 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003838 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003839 cur_var->max_len = strlen(*e);
3840 cur_var->flg_export = 1;
3841 }
3842 e++;
3843 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003844 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003845
Denis Vlasenko38f63192007-01-22 09:03:07 +00003846#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003847 line_input_state = new_line_input_t(FOR_SHELL);
3848#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003849 /* XXX what should these be while sourcing /etc/profile? */
3850 global_argc = argc;
3851 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003852 /* Initialize some more globals to non-zero values */
3853 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003854#if ENABLE_HUSH_INTERACTIVE
3855#if ENABLE_FEATURE_EDITING
3856 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003857#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003858 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003859#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003860
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003861 if (EXIT_SUCCESS) /* otherwise is already done */
3862 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003863
3864 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003865 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003866 input = fopen("/etc/profile", "r");
3867 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003868 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003869 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003870 fclose(input);
3871 }
Eric Andersen25f27032001-04-26 23:22:31 +00003872 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003873 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003874
Eric Andersen25f27032001-04-26 23:22:31 +00003875 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3876 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003877 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003878 global_argv = argv + optind;
3879 global_argc = argc - optind;
Denis Vlasenko5703c222008-06-15 11:49:42 +00003880 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003881 goto final_return;
3882 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003883 /* Well, we cannot just declare interactiveness,
3884 * we have to have some stuff (ctty, etc) */
3885 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003886 break;
3887 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003888 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003889 break;
3890 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003891#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003892 fprintf(stderr, "Usage: sh [FILE]...\n"
3893 " or: sh -c command [args]...\n\n");
3894 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003895#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003896 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003897#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003898 }
3899 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003900#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003901 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003902 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003903 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003904 * no arguments remaining or the -s flag given
3905 * standard input is a terminal
3906 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003907 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003908 if (argv[optind] == NULL && input == stdin
3909 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3910 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003911 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3912 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3913 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003914 /* try to dup to high fd#, >= 255 */
3915 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3916 if (interactive_fd < 0) {
3917 /* try to dup to any fd */
3918 interactive_fd = dup(STDIN_FILENO);
3919 if (interactive_fd < 0)
3920 /* give up */
3921 interactive_fd = 0;
3922 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003923 // TODO: track & disallow any attempts of user
3924 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003925 }
Eric Andersen25f27032001-04-26 23:22:31 +00003926 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003927 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003928 if (interactive_fd) {
Denis Vlasenko08126f62008-02-11 08:39:11 +00003929 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Eric Andersen25f27032001-04-26 23:22:31 +00003930 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003931 setup_job_control();
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00003932 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00003933 * (we reset die_sleep = 0 whereever we [v]fork) */
3934 die_sleep = -1;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003935 if (setjmp(die_jmp)) {
3936 /* xfunc has failed! die die die */
3937 hush_exit(xfunc_error_retval);
3938 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003939#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00003940 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003941 printf("Enter 'help' for a list of built-in commands.\n\n");
3942#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003943 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003944#elif ENABLE_HUSH_INTERACTIVE
3945/* no job control compiled, only prompt/line editing */
3946 if (argv[optind] == NULL && input == stdin
3947 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3948 ) {
3949 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3950 if (interactive_fd < 0) {
3951 /* try to dup to any fd */
3952 interactive_fd = dup(STDIN_FILENO);
3953 if (interactive_fd < 0)
3954 /* give up */
3955 interactive_fd = 0;
3956 }
Denis Vlasenko4830fc52008-05-25 21:50:55 +00003957 if (interactive_fd) {
Denis Vlasenko08126f62008-02-11 08:39:11 +00003958 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenko4830fc52008-05-25 21:50:55 +00003959 set_misc_sighandler(SIG_IGN);
3960 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003961 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003962#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003963
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003964 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003965 opt = parse_and_run_file(stdin);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003966 } else {
3967 debug_printf("\nrunning script '%s'\n", argv[optind]);
3968 global_argv = argv + optind;
3969 global_argc = argc - optind;
3970 input = xfopen(argv[optind], "r");
Denis Vlasenko459a5ad2008-02-11 08:35:03 +00003971 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003972 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003973 }
Eric Andersen25f27032001-04-26 23:22:31 +00003974
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003975 final_return:
3976
Denis Vlasenko38f63192007-01-22 09:03:07 +00003977#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003978 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003979 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003980 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003981 cur_var = top_var->next;
3982 while (cur_var) {
3983 struct variable *tmp = cur_var;
3984 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003985 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003986 cur_var = cur_var->next;
3987 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003988 }
Eric Andersen25f27032001-04-26 23:22:31 +00003989#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003990 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003991}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00003992
3993
3994#if ENABLE_LASH
3995int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3996int lash_main(int argc, char **argv)
3997{
3998 //bb_error_msg("lash is deprecated, please use hush instead");
3999 return hush_main(argc, argv);
4000}
4001#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004002
4003
4004/*
4005 * Built-ins
4006 */
4007static int builtin_true(char **argv ATTRIBUTE_UNUSED)
4008{
4009 return 0;
4010}
4011
4012static int builtin_test(char **argv)
4013{
4014 int argc = 0;
4015 while (*argv) {
4016 argc++;
4017 argv++;
4018 }
4019 return test_main(argc, argv - argc);
4020}
4021
4022static int builtin_echo(char **argv)
4023{
4024 int argc = 0;
4025 while (*argv) {
4026 argc++;
4027 argv++;
4028 }
4029 return echo_main(argc, argv - argc);
4030}
4031
4032static int builtin_eval(char **argv)
4033{
4034 int rcode = EXIT_SUCCESS;
4035
4036 if (argv[1]) {
4037 char *str = expand_strvec_to_string(argv + 1);
4038 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4039 free(str);
4040 rcode = last_return_code;
4041 }
4042 return rcode;
4043}
4044
4045static int builtin_cd(char **argv)
4046{
4047 const char *newdir;
4048 if (argv[1] == NULL) {
4049 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4050 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4051 newdir = getenv("HOME") ? : "/";
4052 } else
4053 newdir = argv[1];
4054 if (chdir(newdir)) {
4055 printf("cd: %s: %s\n", newdir, strerror(errno));
4056 return EXIT_FAILURE;
4057 }
4058 set_cwd();
4059 return EXIT_SUCCESS;
4060}
4061
4062static int builtin_exec(char **argv)
4063{
4064 if (argv[1] == NULL)
4065 return EXIT_SUCCESS; /* bash does this */
4066 {
4067#if !BB_MMU
4068 char **ptrs2free = alloc_ptrs(argv);
4069#endif
4070// FIXME: if exec fails, bash does NOT exit! We do...
4071 pseudo_exec_argv(ptrs2free, argv + 1);
4072 /* never returns */
4073 }
4074}
4075
4076static int builtin_exit(char **argv)
4077{
4078// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4079 //puts("exit"); /* bash does it */
4080// TODO: warn if we have background jobs: "There are stopped jobs"
4081// On second consecutive 'exit', exit anyway.
4082 if (argv[1] == NULL)
4083 hush_exit(last_return_code);
4084 /* mimic bash: exit 123abc == exit 255 + error msg */
4085 xfunc_error_retval = 255;
4086 /* bash: exit -2 == exit 254, no error msg */
4087 hush_exit(xatoi(argv[1]) & 0xff);
4088}
4089
4090static int builtin_export(char **argv)
4091{
4092 const char *value;
4093 char *name = argv[1];
4094
4095 if (name == NULL) {
4096 // TODO:
4097 // ash emits: export VAR='VAL'
4098 // bash: declare -x VAR="VAL"
4099 // (both also escape as needed (quotes, $, etc))
4100 char **e = environ;
4101 if (e)
4102 while (*e)
4103 puts(*e++);
4104 return EXIT_SUCCESS;
4105 }
4106
4107 value = strchr(name, '=');
4108 if (!value) {
4109 /* They are exporting something without a =VALUE */
4110 struct variable *var;
4111
4112 var = get_local_var(name);
4113 if (var) {
4114 var->flg_export = 1;
4115 putenv(var->varstr);
4116 }
4117 /* bash does not return an error when trying to export
4118 * an undefined variable. Do likewise. */
4119 return EXIT_SUCCESS;
4120 }
4121
4122 set_local_var(xstrdup(name), 1);
4123 return EXIT_SUCCESS;
4124}
4125
4126#if ENABLE_HUSH_JOB
4127/* built-in 'fg' and 'bg' handler */
4128static int builtin_fg_bg(char **argv)
4129{
4130 int i, jobnum;
4131 struct pipe *pi;
4132
4133 if (!interactive_fd)
4134 return EXIT_FAILURE;
4135 /* If they gave us no args, assume they want the last backgrounded task */
4136 if (!argv[1]) {
4137 for (pi = job_list; pi; pi = pi->next) {
4138 if (pi->jobid == last_jobid) {
4139 goto found;
4140 }
4141 }
4142 bb_error_msg("%s: no current job", argv[0]);
4143 return EXIT_FAILURE;
4144 }
4145 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4146 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4147 return EXIT_FAILURE;
4148 }
4149 for (pi = job_list; pi; pi = pi->next) {
4150 if (pi->jobid == jobnum) {
4151 goto found;
4152 }
4153 }
4154 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4155 return EXIT_FAILURE;
4156 found:
4157 // TODO: bash prints a string representation
4158 // of job being foregrounded (like "sleep 1 | cat")
4159 if (*argv[0] == 'f') {
4160 /* Put the job into the foreground. */
4161 tcsetpgrp(interactive_fd, pi->pgrp);
4162 }
4163
4164 /* Restart the processes in the job */
4165 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
4166 for (i = 0; i < pi->num_progs; i++) {
4167 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
4168 pi->progs[i].is_stopped = 0;
4169 }
4170 pi->stopped_progs = 0;
4171
4172 i = kill(- pi->pgrp, SIGCONT);
4173 if (i < 0) {
4174 if (errno == ESRCH) {
4175 delete_finished_bg_job(pi);
4176 return EXIT_SUCCESS;
4177 } else {
4178 bb_perror_msg("kill (SIGCONT)");
4179 }
4180 }
4181
4182 if (*argv[0] == 'f') {
4183 remove_bg_job(pi);
4184 return checkjobs_and_fg_shell(pi);
4185 }
4186 return EXIT_SUCCESS;
4187}
4188#endif
4189
4190#if ENABLE_HUSH_HELP
4191static int builtin_help(char **argv ATTRIBUTE_UNUSED)
4192{
4193 const struct built_in_command *x;
4194
4195 printf("\nBuilt-in commands:\n");
4196 printf("-------------------\n");
4197 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4198 printf("%s\t%s\n", x->cmd, x->descr);
4199 }
4200 printf("\n\n");
4201 return EXIT_SUCCESS;
4202}
4203#endif
4204
4205#if ENABLE_HUSH_JOB
4206static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
4207{
4208 struct pipe *job;
4209 const char *status_string;
4210
4211 for (job = job_list; job; job = job->next) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00004212 if (job->alive_progs == job->stopped_progs)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004213 status_string = "Stopped";
4214 else
4215 status_string = "Running";
4216
4217 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4218 }
4219 return EXIT_SUCCESS;
4220}
4221#endif
4222
4223static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
4224{
4225 puts(set_cwd());
4226 return EXIT_SUCCESS;
4227}
4228
4229static int builtin_read(char **argv)
4230{
4231 char *string;
4232 const char *name = argv[1] ? argv[1] : "REPLY";
4233
4234 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4235 return set_local_var(string, 0);
4236}
4237
4238/* built-in 'set [VAR=value]' handler */
4239static int builtin_set(char **argv)
4240{
4241 char *temp = argv[1];
4242 struct variable *e;
4243
4244 if (temp == NULL)
4245 for (e = top_var; e; e = e->next)
4246 puts(e->varstr);
4247 else
4248 set_local_var(xstrdup(temp), 0);
4249
4250 return EXIT_SUCCESS;
4251}
4252
4253static int builtin_shift(char **argv)
4254{
4255 int n = 1;
4256 if (argv[1]) {
4257 n = atoi(argv[1]);
4258 }
4259 if (n >= 0 && n < global_argc) {
4260 global_argv[n] = global_argv[0];
4261 global_argc -= n;
4262 global_argv += n;
4263 return EXIT_SUCCESS;
4264 }
4265 return EXIT_FAILURE;
4266}
4267
4268static int builtin_source(char **argv)
4269{
4270 FILE *input;
4271 int status;
4272
4273 if (argv[1] == NULL)
4274 return EXIT_FAILURE;
4275
4276 /* XXX search through $PATH is missing */
4277 input = fopen(argv[1], "r");
4278 if (!input) {
4279 bb_error_msg("cannot open '%s'", argv[1]);
4280 return EXIT_FAILURE;
4281 }
4282 close_on_exec_on(fileno(input));
4283
4284 /* Now run the file */
4285 /* XXX argv and argc are broken; need to save old global_argv
4286 * (pointer only is OK!) on this stack frame,
4287 * set global_argv=argv+1, recurse, and restore. */
4288 status = parse_and_run_file(input);
4289 fclose(input);
4290 return status;
4291}
4292
4293static int builtin_umask(char **argv)
4294{
4295 mode_t new_umask;
4296 const char *arg = argv[1];
4297 char *end;
4298 if (arg) {
4299 new_umask = strtoul(arg, &end, 8);
4300 if (*end != '\0' || end == arg) {
4301 return EXIT_FAILURE;
4302 }
4303 } else {
4304 new_umask = umask(0);
4305 printf("%.3o\n", (unsigned) new_umask);
4306 }
4307 umask(new_umask);
4308 return EXIT_SUCCESS;
4309}
4310
4311static int builtin_unset(char **argv)
4312{
4313 /* bash always returns true */
4314 unset_local_var(argv[1]);
4315 return EXIT_SUCCESS;
4316}